dqby43944 2013-03-14 11:49
浏览 87
已采纳

如何使用AJAX和JSON发送和接收

I'm trying to setup a simple AJAX call that sends it's data via JSON to my PHP script, which then returns the data.

But I am having no luck.

Here is my code for sending:

$.ajax({
      url: ROOT+'Address/fetchAddress',
      type: 'POST',
      async: false,
      dataType: 'json',
      data: {
        json: {
          "Id":"0",
          "Name":"Jim"
        }
      },
      error: function(a, b)
      {
        alert(b)
      },
      success: function(data)
      {
        data = $.parseJSON(data);
        alert(data)
      }
    })

Serverside:

public function fetchAddress()
  {
    $JSON = $_POST['json'];
    echo json_decode($JSON);
  }

But I am getting "parseerror" in alert box and if I inspect the response I get:

Warning: json_decode() expects parameter 1 to be string, array given in ...public_html\controllers\Address.php on line 20
  • 写回答

3条回答 默认 最新

  • dongzheng4556 2013-03-14 11:52
    关注

    There's a conceptual mistake here.

    When you say dataType: 'json' it means returned data is in JSON format.

    You are still sending data in a POST array

    public function fetchAddress(){
        echo $_POST['json'];
    }
    

    to fetch the data

    To pick up on the other side you have a pre-passed object (as data is returned as JSON)

    So

    success: function(data)
      {
    
        alert(data.id+"NAME"+data.name);
      }
    

    (Oh and your data is not a string (which a post expects) and JSON is so clean it up into a nice string

    json: '{"Id":"0","Name":"Jim"}'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。