簡體   English   中英

通過AJAX檢索PHP JSON數據-數據請求的正確結構

[英]Retrieving PHP JSON data through AJAX - correct structure of data request

我有一個名為terminal_tester.php的PHP文件,該文件運行許多終端操作,並使用以下命令創建json數據

echo json_encode($jsonData);

數據看起來像這樣

{"source":"Betting Tips","published":"2015-05-20 15:20:22;","status":true,"eventIDs":["27448131","27448900"],"TipsTB":"TIP 1 MLADENOVIC TO BEAT RISKE\",\"TIP 2 DOLGOPOLOV TO BEAT GULBIS\"]","TipsTW":"[]"}

我現在想用此數據填充HTML文件,但是在理解Ajax數據輸入的正確格式時遇到了麻煩。 我正在嘗試在我的html文件的腳本區域中進行以下操作

function callbackData(){
    return $.ajax({
        dataType: 'JSON',
        url: 'terminal_tester.php',
        type: 'GET',
        cache: false,
        data: jsonData
    });
};

callbackData().success(function (data) {
    document.getElementById("phpReturn2").innerHTML = jsonData
    document.getElementById("phpReturn3").innerHTML = eventIds
    document.getElementById("phpReturn4").innerHTML = published
});

但我沒有得到任何回應。 我進行了搜索,我認為問題出在ajax請求的data:區域,但也由於PHP文件中需要GET命令而感到困惑。 有人可以解釋如何正確構造ajax請求嗎?

編輯

terminal_tester.php具有很多功能,這些功能最后結合在一起來構建json數據,php文件的最后一部分看起來像這樣

      $jsonData = createJson($eventIds, $TipsTB, $TipsTW, $status);
      echo json_encode($jsonData);
      $fp = fopen('results.json', 'w');
      fwrite($fp, json_encode($jsonData));
      fclose($fp);

首先,我認為您的json數據不正確。 應該像這樣-

{"source":"Betting Tips","published":"2015-05-20 15:20:22","status":true,"eventIDs":["27448131","27448900"],"TipsTB":["TIP 1 MLADENOVIC TO BEAT RISKE","TIP 2 DOLGOPOLOV TO BEAT GULBIS"],"TipsTW":"[]"}

其次,普通的jquery ajax語法是-

$.ajax({
    dataType: 'JSON',  //This means data which come back from terminal_tester.php should be in json format.
    url: 'terminal_tester.php',
    type: 'GET',  // If you are using get request then you should get data by $_GET[]
    cache: false,
    data: {"jsonData":jsonData}, // Edited this from your code.
    success:function(data){ //This data is coming from terminal_tester.php
        alert(data.result);
    }
});

在terminal_tester.php中,應該像這樣-

if(isset($_GET['jsonData'])){
    $jsonData = $_GET['jsonData']; // GET array (Edited)
    // your operation with $jsonData

    // In the end, below json will be get in success data.
    echo json_encode(array('result'=>true));

}

希望這對您有幫助!!

$ .ajax()。success()具有用於訪問從GET請求發送回的數據的data參數。 eventIds和published都是數據的屬性。

callBackData().success(function (data) {

    document.getElementById("phpReturn2").innerHTML = jsonData;
    document.getElementById("phpReturn3").innerHTML = data.eventIds;
    document.getElementById("phpReturn4").innerHTML = data.published;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM