Send Json Array Through jQuery Ajax

情到浓时终转凉″ 提交于 2019-12-06 04:20:00

问题


I am going to send a array of json object through jquery ajax call to a php file.

var arr = new Array();
var record1 = {'a':'1','b':'2','c':'3'};
var record2 = {'d':'4','e':'5','f':'6'};
arr.push(record1);
arr.push(record2);

How can I send the array through jquery ajax? and how can I get the values in php? Thanks.


回答1:


$.ajax({
        url: "api",
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(arr),
        success: function(response){}

       });

And with PHP:

$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);



回答2:


I think JSON.stringify() might be useful.

or, you can use json_decode() in php file.




回答3:


First download and add plugin : jquery.json-2.4.js to your project. This plugin offers a lot of helpers that will make your life easy.

Then in your $.ajax , use data : $.toJSON(arr),




回答4:


The first thing you have to know is that you need to be with two files to make things simple for yourself . 1. Where you going to put your php code phpcode.php 2. Where you going to put your ajax codes ajax.html In the page where you going to put your ajax code make sure you connect to jquery plugins Then

 <script> 
          $(document).ready(function(){
      // your ajax code here  delete mine and put your codes
    $.getJSON(' phpcode.php ', function(data) {
              $('#myJson').html('<table style="color:red"><tr><td>' + data.name + '</td><td>' + data.user + '</td></tr></table>');
            });
          });

        </script>
    <body>
    <!—You may put the bellow div in the ajax page so that u load your data in it ---->
        <div id="myJson"></div>
      </body>
    </html>
     In your php page you need something like this at the end of your code 
    // The JSON standard MIME header.
    header('Content-type: application/json');
    echo  json_encode($array);
    Note: I took an example from my working codes just to save the time but I think you get the Idea


来源:https://stackoverflow.com/questions/14523244/send-json-array-through-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!