我想知道如何在我的jquery.ajax()成功函數中引用特定的變量。在addit.php如何使用jquery.ajax()使用json_encode時返回特定值?
我的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);
}
});
太棒了!得到它的工作。謝謝..警報只是爲了調試。我實際上使用這兩個變量來構造一個URL來重定向用戶,並且它完美地工作。再次感謝。 – 2011-05-24 01:55:06
@bob_cobb太棒了,很高興能有幫助:) – 2011-05-24 01:56:21