Jquery ajax post请求不起作用

2024-06-23 03:15:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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.submitted=post,而不是{“post form”:postcontent}的预期结果。


Tags: forminputreturnifrequest错误ajaxfunction
3条回答

由于发布的是JSON-数据,因此必须声明数据类型“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);
  }

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

Try to change data: {"post-form": postcontent},
To:
data: 'post-form='+ $('.post-form').val(),

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

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

另外,查看服务器端代码,您实际上不想发布JSON格式的数据。这个{"post-form":postcontent}是JSON格式的数据。你真正想做的是发送文本或HTML。看起来是表单数据,我猜是文本。

试试这个:

$.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);
  }
});

相关问题 更多 >

    热门问题