JavaScript和ajax 跨域的案例

时间:2023-12-30 17:45:02

今天突然想看下JavaScript和ajax 跨域问题,然后百度看了一下,写一个demo出来

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/jquery-2.0.3.min.js"></script>
<style type="text/css">
#wrap {
width: 500px;
margin: 200px auto;
} #txtSearch {
width: 400px;
} #mydiv {
width: 400px;
border: 1px solid gray;
} #mydiv ul {
margin: 0px;
padding: 0px;
list-style-type: none;
}
</style>
<script type="text/javascript">
var xhr = createXHR();
function createXHR() {
var request;
if (XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
return request;
}
// xhr.open("get", "http://suggestion.baidu.com/su?wd=" + wd + "&json=1&p=3&sid=&req=2&cb=jQuery110207007932646665722_1411810869509&_=1411810869512", true);
window.onload = function () {
my$("txtSearch").onkeyup = function () {
var wd = this.value;//文本框的值
//判断页面上有没有动态生成的div。如果有删除
var div = my$("mydiv");
if (div) {
my$("wrap").removeChild(div);
} if (wd.length == 0) {
return;
}
yandi = function (data) {
var array = eval(data.s);
if (array && array.length > 0)
{
//动态生成DIV
var div = document.createElement("div");
div.id = "mydiv";
my$("wrap").appendChild(div);
//创建UL
var ul = document.createElement("ul");
div.appendChild(ul);
//创建li
for (var i = 0; i < array.length; i++)
{
var li = document.createElement("li");
li.innerHTML=array[i];
ul.appendChild(li);
//光棒效果
li.onmouseover = function () {
this.style.backgroundColor = "gray";
}
li.onmouseout = function () {
this.style.backgroundColor = "";
}
}
}
}
var url = "http://suggestion.baidu.com/su?wd=" + wd + "&json=1&p=3&sid=&req=2&cb=yandi&_=1411810869512&callback=yandi";
var script = document.createElement("script");
script.setAttribute("src", url);
document.getElementsByTagName("head")[0].appendChild(script);
//ajax跨域
//$.ajax({
// type: "get",
// async: true,
// url: "http://suggestion.baidu.com/su?wd=" + wd + "&json=1&p=3&sid=&req=2&cb=yandi&_=1411810869512",
// dataType: "jsonp",
// jsonp: "callback",
// jsonpCallback: "yandi",
// success: function (data) {
// alert(/2/);
// document.getElementById("11").innerHTML = data.s; // },
// error: function () {
// alert(/11/);
// document.getElementById("11").innerHTML = "111111";
// }
//}); }
//yandi = function (data) {
// var arry = eval(data.s);
// //alert(arry.length);
// alert(data.s);
// document.getElementById("11").innerHTML = data.s;
//}
}; function my$(id) {
return document.getElementById(id);
};
</script>
</head>
<body>
<div id="wrap">
<input type="text" id="txtSearch" /><input type="button" value="search" />
<div id="11"></div>
</div>
</body>
</html>

javascript和ajax跨域代码