批改状态:合格
老师批语:跨域并不高深,其实无处不在
dataType=jsonp,然后设置回调即可,非常方便
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>使用JQuery实现ajax中的get请求</title><script src="js/jquery-3.5.1.js"></script><style>body{display: grid;gap: 5px;}p{background-color: lightseagreen;border-radius: 10px;padding: 10px;}</style></head><body><h1>使用JQuery-ajax-GET-实现无刷新操作</h1><textarea name="content" id="content" cols="30" rows="10" placeholder="输入评论内容"></textarea><button type="button">添加</button><div><span>发送人:</span><span id="sendPerson"></span><p id="showContent" style="height: 100px;"></p><span>发送日期:</span><span id="sendDate"></span></div></form><script>var btn=$('button');btn.click(function(){$.ajax({type:'GET', //异步请求的请求类型url:'ajaxGet.php',//异步请求的请求地址data:{//异步请求的数据content:$('#content').val()},dataType:'json',//异步请求返回值的类型success:function(data){//异步请求成功后的回调函数,data传回来的json数据jquery已经解析好了,直接使用即可$('#sendPerson').text(data['person']);$('#showContent').text(data['content']);$('#sendDate').text(data['date']);$('#content').val("");//设置内容区域为空$('#content').focus();//把焦点设置在内容区域输入}});});</script></body></html>
<?php$add['person'] = 'angle';$add['date'] = date('Y-m-d');$add['content'] = $_GET['content'];$jsonPerson = json_encode($add);echo $jsonPerson;?>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><script src="js/jquery-3.5.1.js"></script><title>JQuery实现跨域请求</title></head><body><h2>JQuery实现跨域请求</h2><div></div><div></div></body><script>$.ajax({type: "GET", //异步请求的请求类型url: "http://58city.com/JQuerydata.php", //异步请求的请求地址// data: {// //异步请求的数据// content: $("#content").val(),// },dataType: "jsonp", //异步请求返回值的类型jsonpCallback: "handle",});function handle(data) {console.log(data);//跨域请求回来的json数据jquery也已经解析完成,直接使用就好$("div:first-of-type").text("姓名:" + data["name"]);$("div:last-of-type").text("年龄:" + data["age"]);}</script></html>
http://58city.com/JQuerydata.php
<?php$stu['name'] = 'Eric';$stu['age'] =6;$jsonStr = json_encode($stu);//handle是请求数据的回调函数名,参数是一个json字符串echo "handle($jsonStr)";?>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号