Php 在jquery.ajax()中使用json_encode时,如何返回特定值?
我想知道如何在jquery.ajax()成功函数中引用特定变量 我在addit.php上的php代码Php 在jquery.ajax()中使用json_encode时,如何返回特定值?,php,jquery,ajax,json,Php,Jquery,Ajax,Json,我想知道如何在jquery.ajax()成功函数中引用特定变量 我在addit.php上的php代码 if ($_POST) { $user_id = $_SESSION['user_id']; $filename = $_SESSION['filename']; $quote = $_POST['quote']; $query = "INSERT INTO `submissions` ( `id` , `user_id`,
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);
}
});
我现在如何在success函数中引用它?我尝试过类似的方法,但没有成功(在警报中返回“undefined”):
似乎响应JSON没有被解析为对象,这就是为什么
alert()
显示整个字符串的原因(否则您会看到[object object]
)。您可以自己解析它,但更好的解决方案可能是执行以下一项(或两项)操作:
dataType=“json”
添加到对ajax()
的调用中,告诉jQuery您希望json作为响应;然后jQuery将解析结果,并为您提供一个data
对象,您可以使用它,而不仅仅是一个字符串。另外,请注意,alert()
只接受一个参数,所有后续参数都将被忽略标题('content-type:application/json')进行响应代码>-这将允许jQuery自动计算出响应是JSON,并为您解析它,而不需要数据类型
值。这也将使其他使用者更容易使用,因为您将显式指定数据类型
我通常使用以下方法来处理返回的json对象:
data = $.parseJSON(data);
然后data.lastID应该返回您期望的lastID值。Awesome!让它工作起来。谢谢该警报仅用于调试。实际上,我正在使用这两个变量来构造一个URL,以将用户重定向到该URL,它工作得非常好。再次感谢。@bob_cobb太好了,很高兴能帮上忙:)