我在下面的ajax调用时遇到了一些麻烦;
function question() {
//ajax call to fetch data from database
var course = "St.Andrews";
var dataString = "course=" + course;
$.ajax({
type: "GET",
url: "http://www.webaddress/fetch.php",
datatype: "json",
data: course,
success: function(datas){
console.log(datas);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("error:" + XMLHttpRequest.responsetext);
}
});
}
由于某种原因,我无法显示获取的结果。我的php文件返回结果工作正常,如果我从浏览器导航到它,我得到有效格式的返回结果。
当我检查控制台日志时,我可以看到参数是正确的,我得到错误:未定义。 任何人都可以提供我做错的事,谢谢。
这是我的php脚本;
<?php
//include databse details
require_once 'login.php';
//connect to database or return error
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("unable to connect to MYSQL:" . mysql_error());
//select database or return error
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_GET['course'])) {
$course = $_GET['course'];
//set the character code
mysql_query('SET CHARACTER SET utf8');
//make the query
$query = "SELECT * FROM questions WHERE course = '" . $course . "' ";
$result = mysql_query($query) or die (mysql_error());
if ($result !== false && mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$question = $row['question'];
$answer = $row['answer'];
$incorrect = $row['incorrectAnswer'];
$difficulty = $row['difficulty'];
//Json row
$json = array ("question" => $question, "answer" => $answer, "incorrect" => $incorrect, "difficulty" => $difficulty);
} else {
//catch any errors
$json = array("error" => "Mysql query error");
}
//set header for json data
header("Content-Type: application/json", true);
//return Json
echo json_encode($json);
} else {
echo "Needs course to advance dingbat";
}
答案 0 :(得分:1)
我看到两种可能性:
1)你的php脚本没有返回有效的json。您指定json
作为数据类型参数,请确保您实际返回json。
2)您违反了相同的原始政策。您的网址为http://www.webadddress/
...除非浏览器从某个网址加载脚本,否则它将无法使用xhr访问该网址。
答案 1 :(得分:1)
最可能的原因是你是从另一个域调用该url而出于安全原因使用普通json是不可能的,你应该使用jsonp。
要纠正: JS
var course = "St.Andrews";
var dataString = {course: course, callback : "?"};
$.ajax({
type: "GET",
url: "http://www.webaddress/fetch.php",
datatype: "jsonp",
data: course,
success: function(datas){
console.log(datas);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("error:" + XMLHttpRequest.responsetext);
}
});
}
PHP
<?php header('content-type: application/javascript; charset=utf-8');
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo $_GET['callback'] . '('.json_encode($data).')';