ajax 跨域访问问题

这两天写一个sina 微博短url 例子。其中利用ajax 跨域访问问题。
成功代码如下:

<html lang="zh" xml:lang="zh" xmlns="http://www.w3.org/1999/xhtml"><head> 
	<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> 
	<meta charset="utf-8"> 
	<title>Tools</title> 
<head>
<script type="text/javascript" src="./jquery-1.6.4.min.js"></script>
<script type="text/javascript">
function short(){
	var url_long=$("#url_long").val();
	var source=$("#source").val();
	var request = "http://api.t.sina.com.cn/short_url/shorten.json?url_long="+url_long+"&source="+source+"&callback=?";
	//&callback=? 必须加上,虽然可以返回数据但success:function 不会调用。jquery api 文档上有说明。
	$.ajax({
		dataType: "jsonp",//跨域访问 dataType 必须是jsonp 类型。
		url: request,
		type:"GET",
		jsonp:"callbackparam",
		jsonpCallback:"success",
		success: function(response) {
			$("#shortUrl").html("短地址为:"+response[0].url_short);
		},
		 error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("status"+XMLHttpRequest.status);
			alert("readyState"+XMLHttpRequest.readyState);
			alert("textstatus"+textStatus);
			alert(errorThrown);
		}
	});
	return false;
}
</script>
</head> 
<body > 
  <div> 
  欢迎使用地址转写工具,请输入链接<br><br>
<form> 
物品链接:<input type="string" name="url_long" id="url_long" /><br> 
APIkey     <input type="string" name="source" value="1681459862" id="source" /><br><br> 
<input type="button" name="submit" value="提交" onclick="short()" /> 
</form> 
</div>
<div id="shortUrl">
</div> 
</body>
注意两点:
1. datatype 必须为jsonp
2.callback=? 必须加上,开始没加上success:function 一直没有响应(返回了数据)。
3.charset="utf-8" 为utf-8 ,文件的保存格式也应该是encoding utf-8 。
如下图所示:
ajax 跨域访问问题_第1张图片
刚开始format 选成了Encode in ANSI  打开网页时出现乱码。
程序运行结果为:
ajax 跨域访问问题_第2张图片

如果采用form 表单提交,不需考虑跨域问题。
代码如下:
<html lang="zh" xml:lang="zh" xmlns="http://www.w3.org/1999/xhtml"><head> 
	<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> 
	<meta charset="utf-8"> 
 
	<title>Tools</title> 
  
</head> 
<body > 
  <div> 
 欢迎使用地址转写工具,请输入链接<br><br> 
<form action="http://api.t.sina.com.cn/short_url/shorten.json" method="get"> 
物品链接:<input type="string" name="url_long" /><br> 
 
     APIkey     <input type="string" name="source" value="1681459862" /><br><br> 
<input type="submit" name="submit" value="提交" /> 
</form> 
</div> 
</body>

你可能感兴趣的:(jsonp,Ajax,String,function,input,XMLhttpREquest)