xmlhttprequest php,php ajax XMLHttpRequest实例

该实例展示了如何通过HTML页面中的Ajax函数向PHP文件发送POST请求,传递表单数据并接收返回的响应。在example.html中,JavaScript函数ajax_post()获取用户输入的firstname和lastname,利用XMLHttpRequest对象发送到my_parse_file.php,PHP文件接收到数据后拼接字符串并返回,更新HTML页面的status元素。
摘要由CSDN通过智能技术生成

本实例有两个文件,一个php处理文件,一个html请求文件。 代码如下:

my_parse_file.php

echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';

?>

example.html

function ajax_post(){

// Create our XMLHttpRequest object

var hr = new XMLHttpRequest();

// Create some variables we need to send to our PHP file

var url = "my_parse_file.php";

var fn = document.getElementById("first_name").value;

var ln = document.getElementById("last_name").value;

var vars = "firstname="+fn+"&lastname="+ln;

hr.open("POST", url, true);

// Set content type header information for sending url encoded variables in the request

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

// Access the onreadystatechange event for the XMLHttpRequest object

hr.onreadystatechange = function() {

if(hr.readyState == 4 && hr.status == 200) {

var return_data = hr.responseText;

document.getElementById("status").innerHTML = return_data;

}

}

// Send the data to PHP now... and wait for response to update the status div

hr.send(vars); // Actually execute the request

document.getElementById("status").innerHTML = "processing...";

}

Ajax Post to PHP and Get Return Data

First Name:  

Last Name:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值