Javascript 带有数据的 jQuery Ajax Post
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42894744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Ajax Post with data
提问by deepak asai
why it isn't working. Am trying to call a php file when onclick of a button occurs with some parameters. It is getting executed till alert statement in jsfile.js. After that the ajax part is not getting executed.. Help me out.. Thanks in advance..
为什么它不起作用。当使用某些参数单击按钮时,我正在尝试调用 php 文件。它正在执行,直到 jsfile.js 中的警报语句。之后,ajax 部分没有被执行.. 帮帮我.. 提前致谢..
main.html
主文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jsfile.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="cart(0)"> hi </button>
<p id="disp"></p>
</body>
</html>
jsfile.js
jsfile.js
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
type:"POST",
data:{
item_id: id,
},
success:function(response) {
//document.getElementById("total_items").value=response;
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
add.php
添加.php
<?php
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
//if(count($_POST)>0)
echo "success";
exit();
}
?>
回答by G Jason Sharma
In your jsfile.js file, please correct the following points which I have mentioned as comments on the following code.
在您的 jsfile.js 文件中,请更正我在以下代码中提到的以下几点。
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
method:"POST", //First change type to method here
data:{
item_id: "id", // Second add quotes on the value.
},
success:function(response) {
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
回答by gudboisgn
Change it and try
改变它并尝试
type:"POST" -> method: "POST"
If your jquery version is >= 1.5 use it this way.
如果您的 jquery 版本 >= 1.5,请以这种方式使用。
$.ajax({
url: "add.php",
method: "POST",
data: { item_id: id},
}).done(function(response) {
......
}).fail(function( jqXHR, textStatus ) {
......
});
Load Jquery Before your JS file.
在 JS 文件之前加载 Jquery。

