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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配