开发者

jQuery load page via ajax and post form inside the returned ajax data

开发者 https://www.devze.com 2023-01-24 03:03 出处:网络
I\'m writing a greasemonkey script to make it so that when a user clicks a checkbox, a page with a form is loaded via .ajax, the form is filled out automatically and then posted.The form is multipart/

I'm writing a greasemonkey script to make it so that when a user clicks a checkbox, a page with a form is loaded via .ajax, the form is filled out automatically and then posted. The form is multipart/form-data which from I've found, can't be posted via the .ajax calls. To get around this, I did the following:

function getConvoPage() {
    $.get("/page_with_form.php", { id: theId }, function(data){
        parsePage(data);
    } );
}

function parsePage(data) {
    var dataObject = jQuery(data);
    dataObject.find('textarea[name="message_text"]').val('Thank you for your purchase!');
    dataObject.find('form[enctype="multipart/form-data"]').submit();
}

I am able to set the value of the textarea and I have confirmed that the form is being found, but the submit action does nothing. I have also tried trigger() and simulating the click() to the submit button. Neither o开发者_如何学Gof these worked, which makes me believe this is just not possible.

What can I do to make this work or what is an alternative approach that will work?


You'll need to add the form to the page in order to post it. In its simplest form, that'll look like this:

function parsePage(data) {
    var dataObject = jQuery(data);
    $('body').append( dataObject );

    dataObject.find('textarea[name="message_text"]').val('Thank you for your purchase!');
    dataObject.find('form[enctype="multipart/form-data"]').submit();
}

If you don't want the form to cause your entire page to be reloaded, then you can create a hidden iframe, add the iframe to the page, then add your form to the iframe. Finally, submit your form, and wait for the iframe's onload event (which can be accomplished with jquery's load() event function.

This latter approach might look something like this:

var asyncSubmitForm = function( form, callback ) {

    var f=$(form).clone();

    // the form is expected to already have the appropriate `action` and `method`
    // attributes set.

    var iframe = $('<iframe id="tempFrame"></iframe>');
    iframe.hide().appendTo('body');
    iframe.load(function() {
        if( callback ) callback(iframe);
        iframe.remove();
        iframe = null;
    });

    iframe.contents().find('body').append(f);
    f.submit();
};

then your parsePage() function would look like this:

function parsePage(data) {
    var dataObject = jQuery(data);

    dataObject.find('textarea[name="message_text"]').val('Thank you for your purchase!');
    asyncSubmitForm(dataObject.find('form[enctype="multipart/form-data"]'), function(iframe) {
       alert('form submitted. response ['+$(iframe).contents().html()+']');
    });
}
0

精彩评论

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