开发者

How do I submit a javascript variable using a round trip to the server

I have a string that I am building via javascript. For the purposes of this example:

var cereal = 'my super cereal string';开发者_JAVA百科

I have a button on the page:

<button id="save" type="submit" name="submit">Save</button>

How do I submit this string using a round trip (I do not want to use ajax). I am using jquery in this application.

What is the best way to accomplish this?


not sure if it's the best or most elegant way, but you could have a form with a hidden field. set the string to the hidden field, and then submit the form.


You could assign a click listener to the button that builds up a throwaway form with an input containing your string:

var cereal = 'my super cereal string';
$("button#save").click(function() {
    var form = "<form id='hidden-form' style='display:none' method='POST' action='/echo/json'><input name='cereal' value='" + cereal + "' /></form>";

    $("body").append(form);
    $("form#hidden-form").submit();
});

Replacing the form's action with whatever you want to POST to.

Check it out: http://jsfiddle.net/andrewwhitaker/MNtwY/


Here's an option using a GET request:

var cereal = 'captain crunch';
$('#save').click(function () {
    window.location.href = "http://www.google.com/search?q=" + cereal;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜