我希望success函数能够获取它应该从PHP文件中收到的字符串。
PHP抱怨“mysql_fetch_array()期望参数1是资源,而是给出布尔值”。我认为这就是成功函数不会触发的原因。
我做错了什么?
jQuery:
var string = "something to be inserted";
$.ajax({
url: '...',
type: 'post',
dataType: 'json',
data: {toBeInserted: string.toLowerCase()},
success: function(data) {
console.log(data);
// some code that is to work with data
}
});
PHP:
include 'serverStuff.php';
// A separate file with $con defined in it. Assume this works.
mysql_query("SET NAMES 'utf8'", $con);
// inserts the $_POST['toBeInserted'] into the database just fine
// assume the following are defined:
// (string) $user_name, (string) $now, (string) $statement
$sql=("SELECT * FROM table WHERE user_name=$user_name AND date=$now AND statement = $statement");
$result=mysql_query($sql, $con);
if ($row = mysql_fetch_array($result)) {
$new_id = (int) $row['id'];
}
mysql_close($con);
echo json_encode($new_id.'_'.$now);
答案 0 :(得分:2)
字符串需要在SQL中进行转义:
"SELECT * FROM table WHERE user_name='$user_name' AND date='$now' AND statement = '$statement'"
它说"布尔给出"因为如果出现错误,则返回the specification false
。 (另请注意注意文档中的弃用说明)
答案 1 :(得分:0)
对于双重双引号问题,请使用:
echo json_encode(array('result' => $new_id.'_'.$now));
JS中的data.result
答案 2 :(得分:0)
好吧,我仍然不确定导致问题的原因,但解决方法如下:
代码:
$.ajax({
// ...
success: function(data) {
console.log(data.responseText);
}
});