<html>
<head>
<script> src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script>
/*$(document).ready(function(){
$("p").click(function(){
event.preventDefault()
$.post("/response.php",
{
name: "Donald Duck",
city: "Duckburg"
},
);
});
});*/
$(document).ready(function(){
$("p").click(function(){
event.preventDefault();
$.ajax({
type: "POST",
url: "/response.php",
data: {name: "Donald Duck", city: "Duckburg"},
cache: false,
success: function(html){
$(".make").html(html);
}
});
});
});
</script>
</head>
<body>
<form action="http://localhost/response.php" />
<p><input type="submit" value="Send an HTTP POST request to a page and get the result back"></p>
</form>
</body>
</html>
嗨,我尝试学习 ajax 将数据从客户端(js,html)发送到服务器(php),我尝试了 ajax。 post(),但是好像从服务器加载数据一样,那么如何让它向服务器发送数据呢?
最佳答案
您将获得未定义的值,因为标准表单提交是在您的 AJAX 发布之前执行的。除了提交按钮之外,您的表单不包含输入,因此不会发送任何数据。您确实设置了 AJAX 来发布值,但永远没有机会执行。
$("form").on("submit", function(event) {
event.preventDefault(); // stop standard form submission
var data = { name: "Donald Duck", city: "Duckburg" };
$.post("/response.php", JSON.stringify(data),
function(result) { });
...
});
您可能还需要这个 handle json request in PHP .
关于javascript - ajax 将数据从客户端(js)发送到服务器(php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29152022/