【问题标题】:Why does this jquery ajax request work with get but not post?为什么这个 jquery ajax 请求可以与 get 一起使用,但不能与 post 一起使用?
【发布时间】:2012-01-17 02:54:03
【问题描述】:
$.ajax({
        url: 'test.php',
        type: 'GET',
        dataType: 'json',
        data: "last_name=SMITH&first_name=JOHN&middle_name=J",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
            var len = response.length;
            for (var i = 0; i < len; i++) {
             var name = response[i].LASTNAME + ", " + response[i].FIRSTNAME + " " + response[i].MIDDLE
             var sysid = response[i].ORDERID
             $("<li></li>")
             .html("<a href='result.php?orderid=" + orderid + "'>" + name + "</a>")
             .insertAfter($("#questions-divider"));
             $("#questions").listview("refresh"); 
            }

        }
   });
});

这适用于 GET。我用post尝试过,但失败了。我的 php 页面中有 _POST。我将数据参数更改为:

data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',

但这也失败了(使用 get 和 post)。我的 php 页面返回它在我的有效负载中找不到 last_name。 $_POST['last_name'] 永远不会在我的 php 页面中获取数据。使用 GET 发送它,它可以工作(我将我的 php 更改为使用 $_GET 进行测试,然后返回到 $_POST)。

编辑:我试过了,但没有帮助:Cant get jQuery ajax POST to work

编辑:也:jquery $.post empty array

编辑:我能够做到这一点。不知道为什么格式化数据失败:

//data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',
    data: "last_name=SMITH&first_name=JOHN&middle_name=J",
    //contentType: "application/json; charset=utf-8",
    contentType: "application/x-www-form-urlencoded",

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    删除引号以使数据的值成为对象。应该读:

    data: { "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" },

    【讨论】:

      【解决方案2】:

      这是我一直使用的简单 $.ajax 模板。它适用于一切。你的数据值应该是一个对象。

      $.ajax({
          type: "POST",
          url: "ajax.php",                             // Your URL
          //data: "action=whatever&user=" + username,  // You can do it like this.
          data: {name: data, action: "whatever"},      // Or like this, Notice the Quotes
          dataType: "html",                            // The Return Type of the data
          success: function(xhr){                      // Success! :)
              alert("success, ajax post was success");
          },
          error: function (xhr, ajaxOptions, thrownError){ // Your a failure :(
              alert(xhr.status);
              alert(thrownError);
          }
      });
      

      您当前将字符串传递给数据,它需要是一个对象:

      您的:

      data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',
      

      应该是

      data: { "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-19
        • 1970-01-01
        • 2015-02-27
        • 2017-05-16
        • 1970-01-01
        相关资源
        最近更新 更多