开发者

AJAX, POST, JSON, and PHP: How do I do it?

How do I send AJAX data through $.ajax() in JavaScript via type: "POST" using JSON data formatting and how do I receive the data in a PHP script (through $_POST??) and put it into an array so I can use it? I've been kicking at this for hours and I have no idea what I'm doing wrong. If someone could post the JS and PHP code for sending and receiving JSON formatted data, I would be eterna开发者_Go百科lly grateful!!!!!

JS Code:

$.ajax({
                type: "POST",
                url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
                data: {
                    "value1": 1,
                    "value2": 2,
                    "value3": 3,
                    "value4": 4,
                    "value5": 5
                },
                dataType: "json"
            });

PHP Code:

I was just using $_POST["value1"], etc., to get that value. On that note, is there a way to make the ajax request GET instead AND open up a new window with that GET data on it so I can see what's going on??


The idea is to create a php page the outputs data in JSON form. This data is taken from an array and echoed using the json_encode function. Using the $.ajax() method from jQuery, you send a request to that page and manipulate the data in the success: function.

Example.

PHP - array.php

$array = ("flag" => 1); 
echo json_encode($array);

JavaScript

$.ajax({
  url : '/array.php', // page containing JSON data
  dataType : 'json', // must be specified for JSON manipulation in success
  success : function(data) { 
       // this function is called if the call to test.php is successful
       // access the data using object dot syntax
       alert(data.flag); // should display '1'
  }
});

// Send data to server this way PHP - test.php

echo $_POST['data'];

JavaScript

$.ajax({
  url : '/test.php',
  dataType : 'text', 
  type : 'post',
  data : { data : 'Hello, World!'},
  success : function(data)          
       alert(data); // should display 'Hello, World'
  }
});


As far as I know you can't POST data in a JSON format. Only as a query string, like GET. You can however return data from the PHP script in a JSON format.

Eg.

$.ajax({
 url: "script.php",
 dataType: 'json', // Tell jQuery/JS that the returned data from script.php is JSON format
 data: 'id='+Id, // will become $_POST['id'] with the value of Id (js var)
 success: function(data){
    // data is JSON formatted
 }

Now, in your PHP script, you receive a POST variable called $_POST['id']. Let's say that $_POST['id'] is needed to request a certain customer from the database. Its data can be stored in an array and then json encoded and then send back to the page with the ajax request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜