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 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题