开发者

Post values with page refresh without using <form>?

开发者 https://www.devze.com 2023-02-20 11:06 出处:网络
With JQuery I can easily do an AJAX post of key value pairs without a form and without a page refresh:

With JQuery I can easily do an AJAX post of key value pairs without a form and without a page refresh:

$.ajax({ type: 'POST', url: url,  data: { key: value, key: value, etc...}  });

But is there a w开发者_JAVA百科ay to post a set of non-form data values with a page refresh, or do I need to take the conventional route of setting up a set of form elements, loading their values, and then submitting the form?

thanks!


You could go the conventional route, but have jQuery build and populate a form dynamically if you wanted to avoid putting a <form> on the page.


You can create dynamic form via jQuery, append it to body and submit it. Disadvantage: you have to generate all fields for it.

$('#Setting_type').change(function () {
    $('<form/>', {
        action: "/postReceiver.php",
        method: "post",
        html: "<input name='Setting[key]' value='"+$('#Setting_key').val()+"'>"
            +"<input name='Setting[type]' value='"+$('#Setting_type').val()+"'>"
            +"<input name='typeChange' value='1'>",
        class: "hidden"
    })
        .appendTo('body')
        .submit()
    ;
});

If you just want to send data via POST but still show params in query, just omit html attribute and put everything in action

$('#Setting_type').change(function () {
    $('<form/>', {
        action: "/postReceiver.php?type="+encodeURIComponent($('#Setting_name').val())
            +"&Setting[key]="+encodeURIComponent($('#Setting_key').val()),
        method: "post",
        class: "hidden"
    })
        .appendTo('body')
        .submit()
    ;
});

.hidden {
    display: none;
}


You could refresh the page after the ajax post:

$.ajax({
    type: 'POST',
    url: url,
    data: {
        key1: value1,
        key2: value2,
        etc...
    },
    complete: function () {
        window.location.reload(true);
    }
});

But what's wrong with doing it the old-fashioned way?

window.location.reload @ MDC


you can always do

window.location = //wherever you want go 

On ajax success

0

精彩评论

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

关注公众号