简体   繁体   中英

Post sign & to another php file

How do i post a string with sign '&' to a php file.

I have a jscript:

function saveRow(oTable, nRow) {
    var jqInputs = $('input', nRow);
    oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
    oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
    oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
    oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
    oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 4, false);
    oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 5, false);
    oTable.fnDraw();
    var val1 = jqInputs[0].value;
    var val2 = jqInputs[1].value;
    var val3 = jqInputs[2].value;
    var val4 = jqInputs[3].value;

    var dataString = 'pairchannels=1' + '&eventname=' + val1 + '&datetime=' + val2 + '&pairedchannel=' + val3 + '&realchannel=' + val4;
    if (val1 == '' || val2 == '' || val3 == '' || val4 == '') {
        alert(jqInputs[1].value);
    } else {
        alert(val1);

        $.ajax({
            type: "POST",
            url: "process.php?",
            data: dataString,
            cache: false,
            success: function(result) {
                alert(dataString);
            }
        });
    }
    return false;
}

Which sends a POST to process.php:

 ...
 else if(isset($_POST['pairchannels'])){
     $this->procPairChannels();
  }
...

function procPairChannels(){
  global $session, $form;
  /* Account edit attempt */
  $retval = $session->procPairChannels($_POST['eventname'], $_POST['datetime'], $_POST['pairedchannel'], $_POST['realchannel']);   

}

But instead of whole string in $_POST['eventname'] which is "Bosnia & Herzegovina" php splits the string at "&". This is the first time error like this occurred because i have never had a "&" in any of my strings until now.

What should i do to handle this kind of strings?

You need to encode the values you are sending in your datastring correctly so that they won't be interpreted as special characters in a url (a & separates key-value pairs...):

The easiest way to do that, is to let jQuery handle that by sending an object instead of a string:

// Maybe a name change to dataObject...
var dataString = {
  pairchannels: 1,
  eventname: val1,
  // etc.
};

If you want to build the query-string yourself you need to use encodeURIComponent() on each individual value.

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