2010-01-26 83 views
2

如果有一個HTML格式如與此html表單提交等效的jQuery ajax是什麼?

<form method="POST" action="http://.../file.php"> 
    <input type="text" name="data" id="data" /> 
    <input type="submit" /> 
</form> 

我想和jQuery的一個AJAX請求,但我不希望使用一種無​​形的形式提交此。但不知何故,我沒有得到它的工作。我的嘗試是

$.ajax({ 
    type: "POST", 
    url: "http://.../file.php", 
    data: d, 
    success: function(msg){ 
     alert("Data Saved: " + msg); 
    } 
}); 

d包含一個JSON對象,我只想粘貼在上面的表單字段爲明文。成功功能得到執行,但我沒有從服務器得到答案(這意味着必須出錯:-)

回答

2

你在同一個域上發佈嗎? Ajax不能跨域使用。

+0

該死的,那實際上是問題所在。如果我通過localhost執行而不是隻打開html「as file」,一切工作正常:-) – 2010-01-26 21:31:50

2

你只需要創建一個JSON對象通過

function postData (data) { 
    $.ajax({ 
     type: "POST", 
     url: "http://.../file.php", 
     data: { data: data }, 
     success: function(msg){ 
      alert("Data Saved: " + msg); 
     } 
    }); 
}; 

postData("xyz"); 

發送或者,如果你想使這個更通用的,你可以做

function postData (data) { 
    $.ajax({ 
     type: "POST", 
     url: "http://.../file.php", 
     data: data, 
     success: function(msg){ 
      alert("Data Saved: " + msg); 
     } 
    }); 
}; 

postData({input1: "x", input2: "y", input3: "z" }); 

最後一個可以讓你更靈活而不必不斷重寫AJAX的輸入。

0

data必須是用於發佈請求成功的一組鍵/值對。您不能指定任意的javascript對象,也不能簡單地將表單中的html作爲字符串粘貼。如果d是除鍵/值對之外的其他值,則您的請求將會出錯。

這裏有一個有效數據對象的例子:

var d = {foo:'bar',fizz:'buzz'}; 
0

jQuery Form Plugin將有助於使你的代碼乾的。

<html> 
<head> 
    <script type="text/javascript" src="jquery-1.3.2.js"></script> 
    <script type="text/javascript" src="jquery.form.js"></script> 

    <script type="text/javascript"> 
     // wait for the DOM to be loaded 
     $(document).ready(function() { 
      // bind 'myForm' and provide a simple callback function 
      $('#myForm').ajaxForm(function() { 
       alert("Thank you for your comment!"); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <form id="myForm" action="comment.php" method="post"> 
     Name: <input type="text" name="name" /> 
     Comment: <textarea name="comment"></textarea> 
     <input type="submit" value="Submit Comment" /> 
    </form> 
</body> 

可在their website更多選擇。