2013-03-26 56 views
0

我一直試圖讓Ajax工作一整天,這是我最後的希望,我寫了一個簡單的測試,看看我是否得到任何迴應,xhr.status是0 200,並且xhr.responseText未被發現。我所說的簡單的(PHP文件),它產生一個JSON對象,我的代碼如下(我試着使用$阿賈克斯,但它並沒有幫助其一):沒有響應形式的ajax和responseText是不明確的

$(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); 

?> 

任何幫助將不勝感激。 Thanx

+0

等一下,所以請問你的PHP文件關聯到你的AJAX開始? – cygorx 2013-03-26 18:18:13

+2

是不是有沒有使用jQuery ajax函數的原因? – Uby 2013-03-26 18:19:49

+0

好ajax發送一個請求到php文件,並且該文件回聲響應json_encoded輸出,如下所示: [{「place_id」:1,「place_name」:「Patidos」,「place_type_id」:0,「street 「:」Jababu街「,」郊區「:」新布萊頓「,」城市「:」伊麗莎白港「,」國家「:」南非「},{」place_id「:2,」place_name「:」桑給巴爾島「 ,「place_type_id」:1,「street」:「Long Street」,「郊區」:「Central」,「city」:「伊麗莎白港」,「country」:「南非」}] @Uby do you have any建議如何使用jQuery Ajax函數,因爲當我使用它們時,我甚至無法使「alert」函數正常工作。 – Emjiz 2013-03-26 18:31:51

回答

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

以及我如何訪問響應,以便我可以在//成功的情況下工作? – Emjiz 2013-03-26 18:48:47

+0

我試過這段代碼,我沒有得到任何輸出,甚至沒有alert()似乎工作, – Emjiz 2013-03-26 19:00:18

+0

我編輯了響應函數,因爲它依賴於我在自己的代碼中傳遞的狀態,但是在這個例子中沒有包括。在瀏覽器中檢查控制檯。它應該打印出響應對象,以便您可以精確地看到返回的參數。 – NateWr 2013-03-26 19:40:15