简体   繁体   中英

javascript post form.submit();

Hi im trying to use javascript to post two strings to another PHP page ( the strings are dynamic and will be created by a JS routine at run time)

I want to use the below code to open a new window and within the code for that page retrieve the posted data

im using the following code to post

var title_string = "title1|title2";
var barcode_string = "barcode1|barcode2";
var path="create_labels.php";
var method = "post";
var params = "titles=" + title_string + "&barcodes=" + barcode_string;
    // The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "_blank");

for(var key in params) {
    if(params.hasOwnProperty(key)) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
     }
}

document.body.appendChild(form);
form.submit();

For simplicity i have just created two strings ( title and barcode) for the time being which i am going to pass via a post on form.submit

The bit im not sure on is the creation of the params, am i doing this correct? The code does open a new window but for whatever reason i am unable to retrieve the posted data, i think im posting it wrong.

Have you seen the output of that form? You are creating hidden fields for each char of the param string. Are you sure you want to do that?

params is a string, not an object, therefore it doesn't have any keys. You end up processing each character of the string and end up with this:

<input type="hidden" name="0" value="t">
<input type="hidden" name="1" value="i">
<input type="hidden" name="2" value="t">
<input type="hidden" name="3" value="l">
<input type="hidden" name="4" value="e">
<input type="hidden" name="5" value="s">
<input type="hidden" name="6" value="=">
<input type="hidden" name="7" value="t">
<input type="hidden" name="8" value="i">
<input type="hidden" name="9" value="t">

... etc...

You may need this bit of code to convert it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM