JSON到PHP的Jquery变量

问题描述:

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:

 $.ajax({
        type: "POST",
        dataType: 'json',
        url: "http://example/ajax",
        data: { test: test },
        cache: false,
        async: true,
        success: function( json ){

            $.each( json.rows, function( i, object ){
                //Example: object.date            
                <?php date('g:ia', $objectDate ) ?>;
            });
        }
    });

What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?

我正在使用Jquery和PHP来进行一些Ajax调用。 这类似于我正在做的事情: p>

  $ .ajax({
 type:“POST”,
 dataType:'json',
 url:“  http:// example / ajax“,
 data:{test:test},
 cache:false,
 async:true,
 success:function(json){
 
 $ .each(json。  rows,function(i,object){
 //示例:object.date 
&lt;?php date('g:ia',$ objectDate)?&gt;; 
}); 
} 
}  ); 
  code>  pre> 
 
 

我需要的是将一些JSON对象传递给PHP,例如 object.date strong>到 $ objectDate 然后用它们做点什么。 这可能吗? p> div>

PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.

You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.

In summary what you should do is:

  1. Pass some data from client to server with an AJAX call
  2. PHP processes these data and returns a JSON object
  3. JS processes the JSON object and, for instance, modifies the HTML of the page.
  4. If you need to further process newly generated data with PHP do other AJAX calls.

Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.

Here's a basic rundown of going from JS to PHP, and PHP to JS:

To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:

var data = { message: "Hello" };
$.ajax({
    data: { data: JSON.stringify(data) },
    // ...
});

Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:

$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"

To send JSON back as the response to the browser (for your success callback), use json_encode like so:

header('Content-type: application/json');
echo json_encode(array(
   'message' => 'Hello, back'
));