0

我一直试图让 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);

?>

任何帮助都感激不尽。谢谢

4

1 回答 1

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);
}

地方.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);
}
于 2013-03-26T18:35:56.760 回答