我想知道如何在我的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`,
`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"}
现在如何在成功功能中引用它?我正在尝试类似的操作,但是没有用(在警报中返回“ undefined”):
$.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);
}
});
参考方案
似乎响应JSON没有被解析为对象,这就是alert()
显示整个字符串的原因(否则您会看到[object Object]
)。您可以自己解析它,但是更好的解决方案可能是执行以下一项(或两项):
将dataType = "json"
添加到对ajax()
的调用中,以告诉jQuery您期望使用JSON作为响应; jQuery然后将解析结果,并为您提供一个可以使用的data
对象,而不仅仅是一个字符串。另外,请注意alert()
仅接受一个参数,所有后续参数都将被忽略。
更新您的PHP以使用正确的内容类型header('Content-type: application/json');
进行响应-这将使jQuery自动确定响应是JSON,它将为您解析该响应,而无需dataType
值。由于您将显式指定数据类型,因此这也将使其他使用者更容易。
JavaScript文件:$.ajax({ type: "POST", url: "ajax.php", data: dataString, success: function(r) { $("#div").html(r); } }); 我想在成功的情况下将页面重定向到new.php,所以在我使用a…
jQuery ajax()返回json对象,但未正确警告 - php为什么无法使用data [0] .id返回ID? $(document).ready(function(){ $.ajax({ type: 'POST', dataType: "json", url: '<?php echo matry::base_to('tests/map_it'…
AJAX实时电子邮件验证(PHP) - php当用户在我的网站上创建帐户时,我希望对照我的数据库(MySQL)中的所有当前用户名检查输入的用户名,并确认是否可用。有谁知道我可以使用的任何好的库,或者是jQuery的插件? 参考方案 所需的确切信息以示例形式here给出。它使用jQuery作为JavaScript库
jQuery Ajax PHP只工作一次 - php我有以下jQuery $("button#submit").click(function(){ $.ajax({ type: "POST", url: "process.php", data: $('form.contact').serialize(), success: fun…
jQuery自动完成ui与json问题 - php我正在尝试使jquery自动完成ui正常工作,但没有成功。没有找到匹配的列表。我收到错误“ TypeError:this.source不是函数”到目前为止,我有一个输入字段<input type="text" id="searchbar" name="title" placeholder=…