2012-07-21 167 views
6

我有一個簡單的表單提交ajax,但它不斷給我一個錯誤。所有錯誤都是「錯誤」。沒有代碼,沒有描述。沒有什麼,當我失敗時提醒它。Jquery ajax發佈請求不起作用

的Javascript使用jQuery:

$(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() 

更新: 經過更多的螢火蟲調試後,我發現post request body包含只有post.submitted = Post,而不是{「post-form」:postcontent}的預期結果。

+0

它是一個JavaScript錯誤(客戶端),服務器錯誤或python錯誤? – Hamish 2012-07-21 21:47:14

+0

@Hamish通過我的調試,我假設這是一個客戶端錯誤。 – Wiz 2012-07-21 22:12:41

回答

14

據​​文檔,您必須聲明中的數據類型:

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

+1這應該做到 – ShadowStorm 2012-07-21 22:00:00

+1

可悲的是,這並沒有工作,但經過一些更多的螢火蟲調試後,我發現帖子主體實際上是後。提交=發佈,而不是預期的post-form = postcontent。 – Wiz 2012-07-21 22:08:14

+0

你真的想發佈JSON還是隻是常規的表單數據? – TheCarver 2012-07-21 22:14:42

1

我認爲問題是您傳遞的數據沒有正確書寫。

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

既然你要發送JSON -data必須聲明具體的數據類型 「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); 
    }