index.js
$(function(){ $(34;.ajax_btn").click(function(){ var xhr = new XMLHttpRequest(); xhr.open("post","http://localhost",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4 && xhr.status == 200) { console.log(JSON.parse(xhr.responseText)); } } xhr.send("info='zsf'"); });});
index.php
<?php$info = $_POST['info']; // 获取前端发来的数据$result = array('code'=>200,'msg'=>'我吸收到的数据为:'.$info);print_r(json_encode($result));?>
注:
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"):ajax利用表单的键值对的形式发送;
$_POST['info']:用来获取前端通报过来的info的属性对应的值,并返回json字符串,前端命利用JSON.parse进行解析。