Target an iframe with a HTML Post with jQuery

前端 未结 7 2255
遥遥无期
遥遥无期 2020-12-08 07:50

If I\'m using jQuery or JavaScript to do a post, how can I make it target an iframe rather than the current page?

jQuery.post( 
    url, 
    [data], 
    [c         


        
相关标签:
7条回答
  • 2020-12-08 08:31

    I know this question is old, but here's how I did it on ASP.Net (C#) using jQuery.

    //Create the form in a jQuery object
    $("<form action='/FormPostTo.aspx' method='post' target='nameofframe'></form>")
        //Get the value from the asp textbox with the ID txtBox1 and POST it as b1
        .append($("<input type='hidden' name='b1' />").attr('value',$('#<%= txtBox1.ClientID %>').val()))
        //Get the value from the asp textbox with the ID txtBox2 and POST it as b2
        .append($("<input type='hidden' name='b2' />").attr('value',$('#<%= txtBox2.ClientID %>').val()))
        //Add the form to the body tag
        .appendTo('body')
        //Submit the form which posts the variables into the iframe
        .submit()
        //Remove the form from the DOM (so subsequent requests won't keep expanding the DOM)
        .remove();
    

    Just a quick note: I did the input tags like that rather than concatenating them, in case the value of the textbox had a quote (') in it. If you concatenated it in, it would mess up the HTML and it wouldn't parse correctly.

    Also, this removes the form from the DOM after it's been used so you don't fill up the DOM with form elements if you post to the iFrame multiple times.

    One slight change that you could make, would be to create the form element if it doesn't exist and then just reference it by ID if it already exists and reuse it.

    0 讨论(0)
提交回复
热议问题