Ext對ajax跨域問題的解決方案

跨域訪問是ajax中比較頭疼的事情。
Ext的Ext.data.ScriptTagProxy對象是用於解決這個問題的。
這個對象實際上做的事情就是使用動態script標籤來處理跨域的請求問題。

[b]script標籤的主要優點在於它並不受Web瀏覽器跨域安全限制的束縛,以及比
XMLHttpRequest具備更好的瀏覽器兼容性。[/b]

[b]ScriptTagProxy的使用方式比較簡單,只用在構造函數中設置一個url。[/b]
示例代碼:
[code] var ds = new Ext.data.Store({
proxy: new Ext.data.ScriptTagProxy({
url: 'http://extjs.com/forum/topics-remote.php'
}),
reader: new Ext.data.JsonReader({
root: 'topics',
totalProperty: 'totalCount',
id: 'post_id'
}, [
{name: 'title', mapping: 'topic_title'},
{name: 'topicId', mapping: 'topic_id'},
{name: 'author', mapping: 'author'},
{name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
{name: 'excerpt', mapping: 'post_text'}
])
});[/code]
[b]這個url返回的應該是javascript類型的內容,java代碼示例:[/b]
[code]boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
scriptTag = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (scriptTag) {
out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (scriptTag) {
out.write(");");
}[/code]
[b]ScriptTagProxy會把這段javascript動態添加到頁面中,如果javascript中的內容是json格式的,
可以用Ext.data.JsonReader進行解析。[/b]
在地址欄中輸入
[url]http://extjs.com/forum/topics-remote.php?callback=strcall1001[/url]
就可以看到ext示例中的返回的javascript內容。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章