Ext对ajax跨域问题的解决方案

跨域访问是ajax中比较头疼的事情。
Ext的Ext.data.ScriptTagProxy对象是用于解决这个问题的。
这个对象实际上做的事情就是使用动态script标签来处理跨域的请求问题。

script标签的主要优点在于它并不受Web浏览器跨域安全限制的束缚,以及比
XMLHttpRequest具备更好的浏览器兼容性。


ScriptTagProxy的使用方式比较简单,只用在构造函数中设置一个url。
示例代码:
    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'}
        ])
    });

这个url返回的应该是javascript类型的内容,java代码示例:
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(");");
}

ScriptTagProxy会把这段javascript动态添加到页面中,如果javascript中的内容是json格式的,
可以用Ext.data.JsonReader进行解析。

在地址栏中输入
http://extjs.com/forum/topics-remote.php?callback=strcall1001
就可以看到ext示例中的返回的javascript内容。

你可能感兴趣的:(JavaScript,Ajax,PHP,json,ext)