我是 ajax 和 jquery 的新手,但我在网上看到了一段代码,我正在对其进行处理以满足我的需要。
唯一的问题是我希望能够从 PHP 响应 ajax。
此 ajax POST 到 php 页面 (email.php)。
如果消息已发送或超过消息限制(我限制每个用户发送的消息数量),我如何使 email.php 回复?
也就是说,我想让ajax从php代码中取一个1或者0,比如:
if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }
这是代码的最后一部分:(如果您需要完整代码,请告诉我)
var data_string = $('form#ajax_form').serialize();
$.ajax({
type: "POST",
url: "email.php",
data: data_string,
success: function() {
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}//end success function
}) //end ajax call
return false;
})
谢谢
最佳答案
$.ajax
的成功
函数调用接收一个参数,通常称为 data
,尽管这取决于你,包含响应,所以:
success: function(data) {
// Use the data
}
(如果需要,它还会接收一些其他参数;更多信息在 the docs 中。)
data
参数的类型将根据您的 PHP 页面发送的响应内容类型而有所不同。如果它发送 HTML,data
将是一个包含 HTML 标记的字符串;如果您的页面发送 JSON ,data
参数将是解码后的 JSON 对象;如果是 XML,data
将是 XML 文档实例。
如果您愿意,您可以使用1
或0
(如果您这样做,我可能会将内容类型设置为“文本/普通”),所以:
success: function(data) {
if (data === "1") {
// success
}
else if (data === "0") {
// failure
}
else {
// App error, expected "0" or "1"
}
}
...但是当我响应 Ajax 请求时,十分之九我会发回 JSON(所以我将 Content-Type
header 设置为 application/json
),因为如果我使用像 jQuery 这样理解 JSON 的库,我会得到一个易于使用的有序对象。我不是 PHP 专家,但我相信您会通过 setContentType
设置内容类型并使用 json_encode
对要发送回的数据进行编码。
在你的情况下,我可能会回复:
{"success": "true"}
或
{"success": "false", "errMessage": "You reached the limit."}
这样服务器端代码就可以指定我向用户显示的错误消息。然后你的 success
函数看起来像这样:
success: function(data) {
var msg;
if (typeof data !== "object") {
// Strange, we should have gotten back an object
msg = "Application error";
}
else if (!data.success) {
// `success` is false or missing, grab the error message
// or a fallback if it's missing
msg = data.errMessage || "Request failed, no error given";
}
if (msg) {
// Show the message -- you can use `alert` or whatever
}
}
关于php - 我如何使用 ajax 从我在此处调用的 php 文件响应 "read"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246772/