Ajax 脚本编写

  • 本文关键字:脚本 Ajax php ajax
  • 更新时间 :
  • 英文 :


例如我有这段代码

<?php 
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>

<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>

我怎么能在 AJAX 中写这样的东西?我不懂这种语言。

我建议使用jQuery。

$.ajax({  //  begins our async AJAX request
type: "POST",  //  defining as POST
url: "goose.php",  //  page to request data from
data: ["goose":$("input[name=goose]").val()],  //  define POST values
success: function(output){
alert(output);
},
error: //do something else
});

由于我们已将类型设置为POST因此我们的数据需要采用关联数组的形式,"goose"等效于$_POST["goose"]

data: ["goose":$("input[name=goose]").val()],

success是如果数据能够正确发送,output是返回的内容,将会发生什么。在我们的例子中,output=<div>goose</div>.

success: function(output){
alert(output);
}

error也可以有一个函数,但在这里你需要告诉脚本如果说goose.php无法访问该怎么办。

不需要额外的框架。只需使用获取 api。

<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>

Javascript:

function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post', 
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}

最新更新