html请求php本页刷新,[HTML/PHP]:中止刷新页面

本文介绍了一种方法,通过JavaScript在前端处理表单验证和POST请求,避免了仅依赖客户端验证的不安全性。通过定义onsubmit函数,构造XMLHttpRequest对象并发送POST请求,可以实现数据的安全传输到PHP服务器。同时,文章还提供了错误处理和响应处理的示例代码,确保了交互的顺利进行。
摘要由CSDN通过智能技术生成

虽然您不应该单独依赖客户端验证,并且绝对应该将所有数据视为PHP中的“脏”,但使用JavaScipt还有另一种方法可以阻止浏览器直接发布表单。不要设置表单的方法和操作,只需定义其onsubmit函数来构造XmlHttpResponse对象,将方法设置为POST并将数据设置为form.serialize(),并发送相应的POST请求。或者,如果PHP脚本将接受GET或REQUEST参数,您可以(在验证之后)构造URL查询并简单地设置window.location以使用适当的数据重定向到PHP页面。

编辑 - 这是我的插图 - 这使用Prototype的Form.serialize function。

Username:

var xhr; // global XMLHttpRequest object

var formElem = $('my_form'); // our form element

function checkUsername() {

var formData = formElem.serialize();

sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);

}

function sendPOSTRequest(toURL, sendData) {

xhr = false;

if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest();

if (http_request.overrideMimeType) {

http_request.overrideMimeType('text/html');

}

} else if (window.ActiveXObject) {

try {

xhr = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xhr = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}

}

}

if (!xhr) {

alert('Cannot create XHR');

return false;

}

xhr.onreadystatechange = handleResponse;

xhr.open('POST', toURL, true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.setRequestHeader("Content-length", sendData.length);

xhr.setRequestHeader("Connection", "close");

xhr.send(sendData);

}

function handleResponse() {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

var result = xhr.responseText;

// result is now whatever content was returned by the PHP script

// do whatever you want with the result here

// for example, you might have the PHP return 'true' or some such thing, and then

// change window.location, or perhaps if it returns 'false' you put up an alert('No!')

// use your imagination, go nuts

} else {

alert('The script returned an error.');

}

}

}

有一些更复杂的方法来创建和处理XMLHttpRequest对象。我可能稍后会发布一些更新的指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值