سؤال

When generating a form using Javascript to post into an iframe, how to POST a single string as value without any attribute name attached to it?

I have this output (In Google Chrome console):

Form data:

data: "{'color': 'blue', 'shape': 'circle'}"

when I am actually looking for:

Form data:

"{'color': 'blue', 'shape': 'circle'}"

My code:

    var f = document.createElement("form");
    var i = document.createElement("input");
    i.setAttribute('type',"text");
    i.setAttribute('name',"data");
    i.setAttribute('value',"{'color': 'blue', 'shape': 'circle'}");
    f.appendChild(i);
    f.submit();

Note that I cannot use regular Xhr Calls at this is a cross domain task.

هل كانت مفيدة؟

المحلول

If I understand you correctly you are trying to deliver a data/json payload using an HTML form. This is impossible, an HTML form can only send data with one of three encoding types (controlled by the enctype attribute on the form), application/x-www-form-urlencoded (the default format for POST), multipart/form-data (necessary when doing file uploads), or text/plain (obsolete, don't use this).

Using AJAX won't help either, cross-domain AJAX is limited to doing exactly what an HTML form can, unless the server sends an Access-Control-Allow-Origin header.

If you have control over the server, you can change the format it expects the data in (or send an Access-Control-Allow-Origin, but that is supported by fewer browsers). If you don't, you can setup a simple API on the server you serve the Javascript from to pass requests through to the other server. Even a simple PHP script would be enough.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top