Jquery Ajax load only works with single word variables
Within my PHP file, I'm passing some variables around from an input box into a link, which loads a page via jQuery's ajax load
function with that variable i开发者_如何学Gon its URL.
This whole system works perfectly, but it only works with single-word variables. Anytime there is a space involved, my Ajax call breaks. I'm assuming this is an encoding issue, but I have some doubts there as well. Basically, it boils down to this line of code in my PHP file which is causing a ruckus.
Is it possible to find out if this is formatted correctly, or why this would break with multi-world queries? The "Keyword" variable has jQuery's trim
function applied to it.
echo $("#addminimal").load("/addmnml?topic='.$_GET['keyword'].'") ;
Thanks.
You don't have to do any encoding at all. Jquery handles it for you:
Here's one way:
echo ' $("#addminimal").load("/addmnml", {topic: "'.$_GET['keyword'].'"}) ';
This works because .load()
accepts a second parameter in an key-value-pair way, and does the encoding for you.
Or better, use php json:
$params = json_encode(array("topic" => $_GET['keyword']));
echo ' $("#addminimal").load("/addmnml", '.$params.') ';
Hope this helps. Cheers
Use encodeURIComponent
to encode spaces before sending to server:
$.ajax
({
type: 'POST',
url: 'APage.aspx',
data: 'word=' + encodeURIComponent('word with space'),
success: function(Data, TextStatus, XHR)
{
},
error: function(XHR)
{
}
});
you need to encode the value...
With PHP:
echo ' $("#addminimal").load("/addmnml?topic='.urlencode($_GET['keyword']).'") ';
or on the javascript side:
echo ' $("#addminimal").load("/addmnml?topic="+encodeUriComponent('.$_GET['keyword'].') ';
Just for the record I used encodeURIComponent as below
d_value = $("#dropdown1").val();
d_value = encodeURIComponent(d_value);
$("#dropdown2").load("drop.php?choice=" + d_value);
It was basically used to populate a 2nd drop down based on the selection of the first drop-down.
精彩评论