<html> <head> <title>js</title> <meta http-equiv=34;Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div> 我是显示内容 </div> <div> <button class="ajax_btn">原生ajax</button> </div> </body> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="./index.js"> </script></html>
index.js
$(function(){ $(".ajax_btn").click(function(){ var xhr = new XMLHttpRequest(); xhr.open("post","http://localhost",true); xhr.setRequestHeader("Content-type","application/json"); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4 && xhr.status == 200) { var info = xhr.responseText; console.log(JSON.parse(info)); } } var data = {"info":"zsf"}; xhr.send(JSON.stringify(data)); });})
index.php
<?phpheader("Access-Control-Allow-Origin:");$info = file_get_contents('php://input'); // 改成这样可以获取到原生发送的application/json$info = json_decode($info,true);$info['age'] = 18;print_r(json_encode($info));?>
注:
xhr.setRequestHeader("Content-type","application/json"):解释我们发送json字符串到后台,以是,利用JSON.stringfy进行转换json字符串。
header("Access-Control-Allow-Origin:"):这里是会涉及到跨域干系;
file_get_contents('php://input'):获取发过来的json串,json_decode转换成php的数组,记住后面的那个 true 值。print_r在php后台进行输出,就会返回到ajax的onreadystatechange回调函数中。