将 json_encode 与 jquery.ajax() 一起使用时如何返回特定值?
我想知道如何在 jquery.ajax() success 函数中引用特定变量。
我的 addit.php 上的 php 代码
if ($_POST) {
$user_id = $_SESSION['user_id'];
$filename = $_SESSION['filename'];
$quote = $_POST['quote'];
$query = "INSERT INTO `submissions` (
`id` ,
`user_id`,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$user_id}', '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
";
$db = DbConnector::getInstance();
$db->insert($query);
// remove funky characters from the quote
$cleanRemove = preg_replace("/[^a-zA-Z0-9\s]/", "", $quote);
// replace any whitespace with hyphens
$cleanQuote = str_ireplace(" ", "-", $cleanRemove);
// get the id of the last row inserted for the url
$lastInsertId = mysql_insert_id();
$returnUrl = array ("lastId"=>$lastInsertId, "cleanQuote"=>$cleanQuote);
echo json_encode($returnUrl);
}
我的 jQuery 代码:
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(msg){
alert(msg);
}
});
在警报中返回:
{"lastId":91,"cleanQuote":"quote-test-for-stack-overflow"}
我现在如何在成功函数中引用它?我正在尝试类似的方法,但它不起作用(在警报中返回“未定义”):
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(data){
alert(data.lastId,data.cleanQuote);
}
});
I'm wondering how to reference specific variables in my jquery.ajax() success function.
My php code on addit.php
if ($_POST) {
$user_id = $_SESSION['user_id'];
$filename = $_SESSION['filename'];
$quote = $_POST['quote'];
$query = "INSERT INTO `submissions` (
`id` ,
`user_id`,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$user_id}', '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
";
$db = DbConnector::getInstance();
$db->insert($query);
// remove funky characters from the quote
$cleanRemove = preg_replace("/[^a-zA-Z0-9\s]/", "", $quote);
// replace any whitespace with hyphens
$cleanQuote = str_ireplace(" ", "-", $cleanRemove);
// get the id of the last row inserted for the url
$lastInsertId = mysql_insert_id();
$returnUrl = array ("lastId"=>$lastInsertId, "cleanQuote"=>$cleanQuote);
echo json_encode($returnUrl);
}
My jQuery code:
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(msg){
alert(msg);
}
});
Returns in the alert:
{"lastId":91,"cleanQuote":"quote-test-for-stack-overflow"}
How can I now reference that in the success function? I was trying something like this, but it didn't work (returns "undefined" in the alert):
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(data){
alert(data.lastId,data.cleanQuote);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
响应 JSON 似乎没有被解析为对象,这就是
alert()
显示整个字符串的原因(否则您会看到[object Object]
)。您可以自行解析它,但更好的解决方案可能是执行以下一项(或两项)操作:将
dataType = "json"
添加到对ajax() 的调用中
告诉 jQuery 您期望 JSON 作为响应;然后 jQuery 将解析结果并为您提供一个可以使用的data
对象,而不仅仅是一个字符串。另请注意,alert()
仅接受一个参数,所有后续参数都将被忽略。更新您的 PHP 以使用正确的内容类型进行响应
header('Content-type: application/json');
- 这将允许 jQuery 自动找出响应是 JSON,并且它将为您解析它,而不需要dataType
值。这也将使其他使用者更容易,因为您将显式指定数据类型。It seems like the response JSON isn't being parsed into an object, which is why the
alert()
displays the entire string (otherwise you'd see[object Object]
). You could parse it on your own but a better solution might be to do one (or both) of the following:Add
dataType = "json"
to the call toajax()
to tell jQuery that you're expecting JSON as the response; jQuery will then parse the result and give you adata
object that you can work with and not just a string. Also, note thatalert()
only accepts one argument, all subsequent ones will simply be ignored.Update your PHP to respond with the correct content type
header('Content-type: application/json');
- this will allow jQuery to automagically figure out that the response is JSON and it will parse it for you, without needing adataType
value. This will also make it easier for other consumers since you'll be explicitly specifying the data type.我通常使用以下方法来处理返回的 json 对象:
然后 data.lastID 应该返回您期望的 lastID 值。
I usually use the following to process the returned json object:
Then data.lastID should return the value you expect for lastID.