AJAX,POST,JSON和PHP:我该怎么做?

时间:2011-09-05 22:16:19

标签: php javascript ajax json post

如何通过JavaScript中的$ .ajax()通过类型发送AJAX数据:使用JSON数据格式的“POST”以及如何在PHP脚本中接收数据(通过$ _POST ??)并将其放入数组,所以我可以使用它?我一直在踢这几个小时,我不知道我做错了什么。如果有人可以发布JS和PHP代码来发送和接收JSON格式的数据,我会永远感激!!!!!

JS代码:

$.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代码:

我只是使用$ _POST [“value1”]等来获取该值。那么,有没有办法让ajax请求改为GET并打开一个带有GET数据的新窗口,这样我就可以看到发生了什么?

2 个答案:

答案 0 :(得分:3)

我们的想法是以JSON格式创建输出数据的php页面。此数据取自数组并使用json_encode函数进行回显。使用jQuery中的$.ajax()方法,您可以向该页面发送请求并操纵success:函数中的数据。

实施例

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'
  }
});

//以这种方式将数据发送到服务器 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'
  }
});

答案 1 :(得分:0)

据我所知,您无法以JSON格式发布数据。仅作为查询字符串,如GET。但是,您可以以JSON格式从PHP脚本返回数据。

例如

$.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
 }

现在,在PHP脚本中,您会收到一个名为$ _POST ['id']的POST变量。 假设从数据库中请求某个客户需要$ _POST ['id']。它的数据可以存储在一个数组中,然后进行json编码,然后通过ajax请求发送回页面。