簡體   English   中英

Ajax,JSON對象與php交互

[英]Ajax, JSON objects interaction with php

我是JSON和Ajax的新手。 基本上,我試圖從mysql數據庫中獲取事件列表,並將它們作為JSON編碼的文件發送回.ajax()並從該函數顯示那些事件列表。 我嘗試了不同的方法,但我不認為自己走在正確的道路上。 作為Ajax和JSON的新手,使用Ajax發送和接收數據有些混亂,但很有趣

JSON對象和數組使我感到困惑,我不知道如何訪問內部元素而感到震驚

$.ajax({ 
...
...
...
})
.done(function(result)
{
})

result是對象還是數組或字符串? 我應該在這里使用JSON.parse()方法還是應該將result直接用於數據的處理和顯示?

這是我的后端php文件的輸入格式,

{"data": 
    {
        "dept": "CSE"
    }
}

此輸入來自一個下拉列表,

$("#dept_drop_down").on("change", function() {
...
...
})

我的php文件的輸出格式是

{
  "data": {
    "status": "success",
    "response_code": "202",
    "events": {
      "1": {
        "name": "Help Dexter",
        "desc": "Help Dexter to Solve the Puzzle",
        "coordinate": "1307",
        "dept": "CSE"
      },
      "2": {
        "name": "Code Hunt",
        "desc": "Lets hunt the CODE ..!!",
        "coordinate": "2145",
        "dept": "CSE"
      }
    }
  }
}

請幫助我使用JavaScript代碼,以發送輸入格式JSON和接收輸出格式JSON並使用AJAX(上面給出的輸入和輸出格式)顯示它們。

等待您的幫助。 提前致謝...

這是我的代碼...

$(document).ready(function(){ 
    $("#dept_drop_down").on("change", function(){ 
        var dat = $(document.getElementById("dept")).serializeJSON();
        var postdata = JSON.stringify(dat); 
        $.ajax({ 
            url: "elist.php", 
            type: "POST", 
            data: postdata, 
            datatype: 'application/json', 
            error: function(xhr,a,b){alert("This is "+xhr.status)}, 
            beforeSend: function(){alert("Sending.......")}, 
            success:function(result){ 
                var obj=result; 
                d=$.parseJSON(result); 
                if(obj.data.resopnse_code==202)
                { 
                    //object processing .. Here is the place i need help
                }
                else if(obj.data.response_code==200)
                { 
                    //object processing .. Here is the place i need help
                } 
                else if(obj.data.response_code==201)
                { 
                    //object processing .. Here is the place i need help
                } 
                else if(obj.data.response_code==400)
                { 
                    //object processing .. Here is the place i need help
                } 
            }    
        });     
    }); 
});

結果是一個字符串。 您可以使用jQuery.parseJSON制作一個JSON對象。

var jsonObj = jQuery.parseJSON( result );

您可以使用創建的變量(在我的示例jsonObj中 )和元素的名稱訪問內部元素。

假設您要在JSON中使用第二個事件的坐標,請使用

jsonObj.events.data[1].coordinate

那是:

  • jsonObj:訪問主要的JSON對象
  • 數據:訪問jsonObj中的數據元素
  • 事件:訪問數據中的 事件
  • 1 :訪問事件元素中的1個元素
  • 坐標: 第二個事件元素中的訪問坐標

那將返回字符串“ 1307”

總體而言,獲得Ajax並不難,而且您似乎已經對此有所了解。

這是一個操場: http : //codepen.io/anon/pen/WrZQrj

好吧,這完全取決於您的PHP腳本以Content-Type返回給調用的內容。 例如,假設我們在上面包含一個包含您的對象文本的json.json文件,我可以這樣編寫PHP腳本:

<?php

$content =file_get_contents ('json.json') ;
echo $content ; // I echo a string here
die ;

Ajax調用將收到一個文本字符串,因為該調用默認為text / plain Content-Type

$.post ('php.php', {}, function (ret, status) {
    alert (ret) ; // Will alert text
    if ( typeof ret === 'string' )
        ret =JSON.parse (ret) ;
    alert (ret) ; // Will alert [Object] [Object]
    // ret.data.status == 'success'
}) ;

現在,如果我的PHP腳本執行以下操作:

<?php

$content =file_get_contents ('json.json') ;
header ('Content-Type: application/json') ;
echo $content ; // I echo a string here still
die ;

他們有區別。 現在,我得到了一個JSON對象:

$.post ('php.php', {}, function (ret, status) {
    alert (ret) ; // Will alert [Object] [Object]
    if ( typeof ret === 'string' ) // << will not execute anymore
        ret =JSON.parse (ret) ;
    alert (ret) ; // Will alert [Object] [Object]
    // ret.data.status == 'success'
}) ;

我在第二個中保留了if()和JSON.parse(),但在最后一種情況下不再使用它們。

最后一件事,在PHP代碼中,我回顯了一個來自文件的字符串,但是如果您有一個由腳本構建的對象,則代碼如下

$content =(object)[] ;
$content.data =(object)[ "status" => "success" } ;
...
header ('Content-Type: application/json') ;
echo json_encode ($content) ; // I echo a string here
die ;

暫無
暫無

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

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