Access json data from php

前端 未结 3 1867
野性不改
野性不改 2021-01-17 00:32

I have a problem accessing JSON data. I\'m new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.

My jQuery:



        
相关标签:
3条回答
  • 2021-01-17 01:08

    I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:

      $.post(
        "currentPage.php",
        { 
        'currentPage': 1
        },
        function(data){
          $("body").append(data);  
        },
        "json"
      );
    
    0 讨论(0)
  • 2021-01-17 01:18

    In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:

    "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

    You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.

    $.ajax({
        url: "currentPage.php",
        data: { 
            'currentPage': 1
        },
        dataType: "json",
        type: "post",
        success: function(data) {
            $("body").append(data);  
        }
    });
    
    0 讨论(0)
  • 2021-01-17 01:28

    Provide the datatype you expect to get as parameter to the .post() method (in your case json):

    $.post("currentPage.php",{'currentPage': 1},
      function(data){
        $("body").append(data);  
      },
      'json'     // <-- add the expected datatype
    );
    

    I think the default is to treat the result as HTML. Read the documentation.

    jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )

    urlA string containing the URL to which the request is sent.

    dataA map or string that is sent to the server with the request.

    success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.

    dataType The type of data expected from the server.

    0 讨论(0)
提交回复
热议问题