优秀的编程知识分享平台

网站首页 > 技术文章 正文

web开发之-ajax的基本使用(处理json数据)

nanyue 2024-10-03 23:36:59 技术文章 5 ℃

什么是ajax?

ajax就是一个异步的javascript和xml,你可以不要太在意书面上的意思,你要知道,我们向后台请求数据,除了基本的form表单外,大多数情况下我们是使用的ajax向后台发送请求,ajax比form表单的功能更强大!

ajax基本格式

var xhr = new XMLHttpRequest();
        xhr.open(请求方多,请求地址,是否异步); // 请求方式,请求地址,是否异步
        xhr.setRequestHeader("Content-type","application/json"); // 设置请求头
        xhr.onreadystatechange = function(e)
        {
            if(xhr.readyState == 4 && xhr.status == 200)
            {
                var info = xhr.responseText; // 返回的数据
            }
        }
        var data = {"info":"zsf"}; // 发送给后台的数据
        xhr.send(JSON.stringify(data));

ajax发送json数据

index.html

<html>
    <head>
        <title>js</title>
        <meta http-equiv="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

<?php
header("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回调函数中。

最近发表
标签列表