php querystring,PHP: urlencode - Manual

When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or POST with content-type header set to 'x-www-form-urlencoded') you must urlencode your data before you upload it.  (In fact, if you don't urlencode POST data MS Internet Explorer may pop a "syntax error" dialog when you call XMLHttpRequest.send().)  But, you can't call PHP's urlencode() function in Javascript!  In fact, NO native Javascript function will urlencode data correctly for form submission.  So here is a function to do the job fairly efficiently:

// PHP-compatible urlencode() for Javascript

function urlencode(s) {

s = encodeURIComponent(s);

return s.replace(/~/g,'%7E').replace(/%20/g,'+');

}

// sample usage:  suppose form has text input fields for

// country, postcode, and city with id='country' and so-on.

// We'll use GET to send values of country and postcode

// to "city_lookup.php" asynchronously, then update city

// field in form with the reply (from database lookup)

function lookup_city() {

var elm_country = document.getElementById('country');

var elm_zip = document.getElementById('postcode');

var elm_city = document.getElementById('city');

var qry = '?country=' + urlencode(elm_country.value) +

'&postcode=' + urlencode(elm_zip.value);

var xhr;

try {

xhr = new XMLHttpRequest(); // recent browsers

} catch (e) {

alert('No XMLHttpRequest!');

return;

}

xhr.open('GET',('city_lookup.php'+qry),true);

xhr.onreadystatechange = function(){

if ((xhr.readyState != 4) || (xhr.status != 200)) return;

elm_city.value = xhr.responseText;

}

xhr.send(null);

}

******/?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值