Post data to JsonP

后端 未结 7 1441
傲寒
傲寒 2020-11-22 07:22

Is it possible to post data to JsonP? Or does all data have to be passed in the querystring as a GET request?

I have alot of data that I need to send to the service,

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:07

    I know this is serious necromancy, but I thought I'd post my implementation of JSONP POST using jQuery, which I'm successfully using for my JS widget (this is used for customer registration and login):

    Basically, I'm using an IFrame approach, as suggested in the accepted answer. What I'm doing differently is after sending the request, I'm watchin, if the form can be reached in the iframe, using a timer. When the form cannot be reached, it means the request has returned. Then, I'm using a normal JSONP request to query for the status of the operation.

    I hope that someone finds it useful. Tested in >=IE8, Chrome, FireFox and Safari.

    function JSONPPostForm(form, postUrl, queryStatusUrl, queryStatusSuccessFunc, queryStatusData)
    {
        var tmpDiv = $('
    '); form.parent().append(tmpDiv); var clonedForm = cloneForm(form); var iframe = createIFrameWithContent(tmpDiv, clonedForm); if (postUrl) clonedForm.attr('action', postUrl); var postToken = 'JSONPPOST_' + (new Date).getTime(); clonedForm.attr('id', postToken); clonedForm.append(''); clonedForm.attr('id', postToken ); clonedForm.submit(); var timerId; var watchIFrameRedirectHelper = function() { if (watchIFrameRedirect(iframe, postToken )) { clearInterval(timerId); tmpDiv.remove(); $.ajax({ url: queryStatusUrl, data: queryStatusData, dataType: "jsonp", type: "GET", success: queryStatusSuccessFunc }); } } if (queryStatusUrl && queryStatusSuccessFunc) timerId = setInterval(watchIFrameRedirectHelper, 200); } function createIFrameWithContent(parent, content) { var iframe = $(''); parent.append(iframe); if (!iframe.contents().find('body').length) { //For certain IE versions that do not create document content... var doc = iframe.contents().get()[0]; doc.open(); doc.close(); } iframe.contents().find('body').append(content); return iframe; } function watchIFrameRedirect(iframe, formId) { try { if (iframe.contents().find('form[id="' + formId + '"]').length) return false; else return true; } catch (err) { return true; } return false; } //This one clones only form, without other HTML markup function cloneForm(form) { var clonedForm = $('
    '); //Copy form attributes $.each(form.get()[0].attributes, function(i, attr) { clonedForm.attr(attr.name, attr.value); }); form.find('input, select, textarea').each(function() { clonedForm.append($(this).clone()); }); return clonedForm; }

提交回复
热议问题