开发者

What is the jQuery ajax equivalent to this html-form submit?

If have a html form like

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

I want to make a ajax-request with jQuery, but I don't want to use an invisible form to s开发者_高级运维ubmit this. But somehow I don't get it to work. My try was

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

were dcontains a JSON object which I would just paste in the above form field as plaintext. The success function gets executed, but I don't get the answer from the server (which means that something must go wrong :-)


Are you POSTing on the same domain? Ajax doesn't work cross-domain.


You just need to create a json object to send through

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

postData("xyz");

Or if you wanted to make this more generic you can do

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" });

The last one allows you to be more flexible and not have to constantly rewrite the inputs to the AJAX.


data must be a set of key/value pairs for the post request to be successful. You can not specify an arbitrary javascript object, nor can you simply paste in the html from your form as a string. If d is anything other than a key/value pair set, your request will error.

Here's an example of a valid data object:

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


jQuery Form Plugin will help make your code DRY.

<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>

More options available at their website.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜