2013-11-22 132 views
4

我正在寫一個函數將數據從表單發佈到休息api。這是我的,但它不工作,我不知道爲什麼。使用jquery POST休息api

<script> 
    console.log(document); 
    var form = document.getElementById("myform"); 

    form.onsubmit = function (e) { 
     // stop the regular form submission 
     e.preventDefault(); 

     // collect the form data while iterating over the inputs 
     var data = {}; 
     for (var i = 0, ii = form.length; i < ii; ++i) { 
     var input = form[i]; 
     if (input.name) { 
      data[input.name] = input.value; 
     } 
     } 

    function addData(){ 
    $.ajax({ 
      type: "POST", 
      url: "http://example.com", 
      data: JSON.stringify(data), 
      contentType: "application/json; charset=utf-8", 
      crossDomain: true, 
      dataType: "json", 
      success: function (data, status, jqXHR) { 

       alert(success); 
      }, 

      error: function (jqXHR, status) { 
       // error handler 
       console.log(jqXHR); 
       alert('fail' + status.code); 
      } 
      }); 
    } 
</script> 

任何人都可以指向正確的方向嗎?

+0

什麼是你正在得到的錯誤 – naveen

+0

我沒有得到一個錯誤。當我在瀏覽器中運行頁面時,點擊檢查元素並查看「網絡」下發生了什麼,然後單擊我應該運行的「添加」按鈕,但沒有任何反應! – bookthief

回答

1

您還沒有form.onsubmit事件調用addData()

form.onsubmit = function (e) { 
    // stop the regular form submission 
    e.preventDefault(); 

    // collect the form data while iterating over the inputs 
    var data = {}; 
    for (var i = 0, ii = form.length; i < ii; ++i) { 
    var input = form[i]; 
    if (input.name) { 
     data[input.name] = input.value; 
    } 
    } 
    addData(); 
} 
+0

謝謝,但它仍然不會工作? – bookthief

+0

它現在有效,我放了一個支架,當我把它放進去,歡呼聲 – bookthief

+0

@bookthief,乾杯:) –

5

calllike下面

addData(data); 

function addData(data){// pass your data in method 
    $.ajax({ 
      type: "POST", 
      url: "http://example.com", 
      data: JSON.stringify(data),// now data come in this function 
      contentType: "application/json; charset=utf-8", 
      crossDomain: true, 
      dataType: "json", 
      success: function (data, status, jqXHR) { 

       alert("success");// write success in " " 
      }, 

      error: function (jqXHR, status) { 
       // error handler 
       console.log(jqXHR); 
       alert('fail' + status.code); 
      } 
      }); 
    } 
+0

謝謝,但服務器仍然沒有迴應? – bookthief