阻止action属性使用javascript运行php脚本

阻止action属性使用javascript运行php脚本,javascript,php,html,Javascript,Php,Html,是否有一种方法可以使用javascript防止表单运行php脚本。例如,类似这样的事情: <form action="somePage.php" method="POST> <input type= "text" class= "field" name = "blah"> <input type="submit" value="Send" > </form> 您可以将函数附加到表单的提交事件: document.getElementByI

是否有一种方法可以使用javascript防止表单运行php脚本。例如,类似这样的事情:

<form action="somePage.php" method="POST>

<input type= "text" class= "field"  name = "blah">

<input type="submit" value="Send" >

</form>

您可以将函数附加到
表单的
提交
事件

document.getElementById('form-id').addEventListener("submit", function(e){
    var field1 = getElementById('field1').value;
    if(field1=='' || field1 == null){
      e.preventDefault();
      alert('Pls fill the required fields.');
      return;
    }
    return true;
});

以下解决方案使用内联js:

如果要在将表单提交到php脚本之前运行js函数,可以使用表单的
onsubmit
属性

<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">

  <input type= "text" class= "field" id="field1"  name = "blah">

  <input type="submit" value="Send" >

</form>

您只需抓取表单(我使用了
querySelector
,因为您没有ID或类),然后添加一个提交侦听事件以返回false,从而为提交事件
返回false

var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
    return false;
});

您可以在somePage.php中使用以下新的子句:

if(empty($_POST['blah'])){
  die();
}
或者与之相反

if(!empty($_POST['blah'])){
  //do what this php is supposed to
}
else{
  //display error
}
如果未填写该字段,这将阻止php运行


就我个人而言,我会将它们返回到同一页面,并在页面上设置一些错误。

使用此代码防止表单提交:

var first_form = document.getElementsByTagName('form')[0];

first_form.addEventListener('submit', function (e) {
    e.preventDefault();      //This actually prevent browser default behaviour
    alert('Don\'t submit');
    //Do your stuff here
}, false);

更好的阅读

问题是如何使用javascript阻止PHP脚本,请仔细阅读此阻止表单如何提交?没关系,谢谢您的建议。代码在我的书中总是可以接受的,即使它不是我所要求的。在另一种情况下,它可能会有所帮助。似乎它可以奏效。我来试试你有没有测试过这个代码?不在这里工作。我试过了,但没有。也许我错过了一些东西。我想投票,但我不能,因为你提倡内联javascript。嗯?我不明白@Rao检查一下这个文件的格式。避免使用内联事件监听器。我的印象是,如果我不在脚本中添加标记,那么就不知道代码使用的是哪种语言。而且不会正确地对其进行颜色编码。@Rao
onsubmit=return function()
您能建议对我的答案进行编辑吗?如何避免内联js?我不应该;t使用onsubmit=“”是吗?
var first_form = document.getElementsByTagName('form')[0];

first_form.addEventListener('submit', function (e) {
    e.preventDefault();      //This actually prevent browser default behaviour
    alert('Don\'t submit');
    //Do your stuff here
}, false);