我一直试图让ajax工作一整天,这是我最后的希望,我写了一个简单的测试,看看我是否得到任何响应,xhr.status是0而不是200,以及xhr.responseText是未定的。我调用一个生成json对象的简单(php文件),我的代码如下(我尝试使用$ .ajax,但它也没有帮助):
$(function(){
$('#checkin').click(function(){
var ajaxRequest;
var connection = ajaxFunction();
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.open("GET", "places.php", true);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(console.error(ajaxRequest.status));
}
}
ajaxRequest.send(null);
}
});
})
我的php文件如下:
<?php
header('Content-type: application/json');
require "SQLquery.php";
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
?>
任何帮助将不胜感激。感谢名单
答案 0 :(得分:0)
这是一个使用jQuery的$ .ajax()和json。
的简单实现使用Javascript:
function sendAjax() {
// The data you want to pass to places.php
var params = {
'checkin' : true
};
// Construct the call
ajax = $.ajax({
url: '/places.php',
type: 'GET',
data: params,
dataType: 'json'
});
// Send it and say which function you'll
// use to handle the response
ajax.done(sendAjaxDone);
}
// Handle the response
function sendAjaxDone(response) {
console.log(response);
}
places.php
header('Content-type: application/json');
require "SQLquery.php";
if ($_GET['checkin']) {
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
}