Jquery ajax发布请求不起作用

Jquery ajax post request not working

本文关键字:请求 不起作用 ajax 布请求 Jquery      更新时间:2023-12-17

我用ajax提交了一个简单的表单,但它总是给我一个错误。所有的错误都是"错误"。没有代码,没有描述。没有什么,当它失败时我会提醒它。

带有jQuery的Javascript:

$(document).ready(function(){
        $(".post-input").submit(function(){
            var postcontent = $(".post-form").val();
            if (postcontent == ""){
                return false;
            }
            $(".post-form").attr("disabled", "disabled");
            $.ajax({
                url: '/post',
                type: 'POST',
                data: {"post-form": postcontent},
                dataType: json,
                success: function(response, textStatus, jqXHR) {
                    alert("Yay!");
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert(textStatus, errorThrown);
                }
            });
        });
    });

HTML:

<form class="post-input" action="" method="post" accept-charset="utf-8">
                <textarea class="post-form" name="post-form" rows="1" cols="10" onFocus="this.value='';return false;">What are you thinking about...</textarea>
                <p><input class="post-submit" type="submit" name = "post.submitted" value="Post"></p>
            </form>

如果没有问题,那么服务器端(金字塔):

def post(request):
    session = Session()
    user = authenticated_userid(request)
    postContent = request.POST['post-form']
    if not postContent == '':
        session.add(Activity(user.user_id, 0, postContent, None, None))
        return {}
    return HTTPNotFound()

更新:在用firebug进行了更多的调试后,我发现post请求体只包含post.submited=post,而不是{"post-form":post-content}的预期结果。

根据jQuery文档,您必须声明数据类型:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

此外,查看服务器端代码,实际上并不希望发布JSON格式的数据。此{"post-form":postcontent}是JSON格式的数据。您实际想要做的是发送TEXT或HTML。看起来是表单数据,我猜是TEXT。

试试这个:

$.ajax({
   url: '/post',
   type: 'POST',
   data: 'post-form='+postcontent,
   dataType: 'text',
   success: function(response, textStatus, jqXHR) {
     alert("Yay!");
   },
   error: function(jqXHR, textStatus, errorThrown){
     alert(textStatus, errorThrown);
  }
});

由于您发布的是JSON-数据,因此您必须声明dataType"JSON":

$.ajax({
  url: '/post',
  type: 'POST',
  dataType: "json",
  data: {"post-form": postcontent},
  success: function(response, textStatus, jqXHR) {
    alert("Yay!");
  },
  error: function(jqXHR, textStatus, errorThrown){
    alert(textStatus, errorThrown);
  }
});

我认为问题在于您传递的数据没有正确写入。

尝试改变这个:

data: {"post-form": postcontent},

对此:

data: 'post-form='+ $('.post-form').val(),