【问题标题】:ajax post not sending dataajax post不发送数据
【发布时间】:2013-11-19 21:47:53
【问题描述】:

更新:我想通了。是一个 URL 问题,它在将 POST 发送到服务器之前重定向并清除了它。

$('#addbtn').on('click',function() {

$.ajax({
  type: "POST",
  url: "/create/",
  dataType: "json",
  data: $('#MultiAdd').serializeArray(),
  success: function (data) {
    // this returns Failed. Please Try Again. c_name=
    // c_name should equal the value from post. 
    alert(data.msg)
  },
  error: function (xhr, ajaxOptions, thrownError) {}
 });

});

我似乎无法让这个发布数据。我尝试了很多变化。看了好几个小时,想看看有什么问题。

我试过data: {test:'test'}(没用)

GET 函数可以,但我需要它是 POST。 我也尝试过正常的.serialize()。仍然没有工作。

这确实可以向我展示价值观。但 ajax 不会在提交中发布它们。

console.log($('#MultiAdd').serializeArray());

(在页面上,表单和ajax代码是动态添加的,但我认为不会有太大变化,我已经测试过了。)

更新:(我正在使用 codeigniter)- 服务器端。尝试访问 [input name="c_name"]

public function create()
{
   $value = $this->input->post('c_name');

   $msg = array("msg"=>"Failed. Please Try Again. c_name=".$value); 

   die(json_encode($msg)); 
 }

【问题讨论】:

  • 你试过完整的网址吗?
  • 是的,网址有效,我已经发送了 GET 测试,并且发送了值。它的 POST 我似乎无法发送值
  • 你能告诉我们你的服务器端代码吗?
  • 你怎么知道数据没有被发送?
  • 你能澄清一下出了什么问题吗?是否将 POST 发送到服务器,但不发送数据?它发送的是什么?

标签: jquery ajax post serialization


【解决方案1】:

如果 GET 请求有效,但 POST 无效,这通常是重定向的问题。也就是说,虽然请求最初访问了第一个 URL 并被重定向到另一个 URL,但所有 POST 数据都没有转发到另一个 URL。因此所有数据都会丢失。

可能发生的一些常见情况(取决于服务器配置):

  • "/method/" 可能会被您的网站重定向到 "/somethingCompletelyElse/"
  • "/method" 可能会被您的网站重定向到 "/en/method"(语言重定向)
  • "method/" 可能会被您的网站重定向到 "method"
  • "method" 可能会被您的网站重定向到 "method/"(常见,额外的反斜杠)
  • “example.com/method” 可能会被您的网站重定向到 “www.example.com/method”

你明白了。如果您查看 network panel 并注意到没有发送数据但响应为 200 OK,那么最好检查一下 network 面板中的 Request URL 是否是您的在您的代码中指定。尽管这仅在现代浏览器中才有可能。在旧版浏览器中,您甚至不会知道 URL 已被重定向。

例如(请参阅我的请求网址中缺少“en/”):

【讨论】:

    【解决方案2】:

    尝试将contentType 添加到application/x-www-form-urlencoded

    $.ajax({
      type: "POST",
      url: "/create/",
      dataType: "json",
      data: $('#MultiAdd').serializeArray(),
      contentType: "application/x-www-form-urlencoded",
      success: function (data) { //success },
      error: function (xhr, ajaxOptions, thrownError) { //some sort of error }
     });
    

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多