0

我正在尝试从我的 jQuery 移动网站中的 javascript 文件中检索信息。默认情况下启用 Ajax,但是当我尝试使用 xmlHttpRequest.send() 时,responseText 是页面的源代码,而不是 json 结构。initialize() 函数在 pageinit 处运行,所以我的想法是它正在检索的 json 在调用时应该存在。此外,initialize() 在网站的非移动版本上也能正常工作,所以我认为它与 JQM 如何处理 ajax 请求有关。提前感谢您的任何帮助。

<!DOCTYPE html>
<html>
    <head>
        var xmlHttpRequest;
        var json;

        <script type="text/javascript">
            function initialize()
            {
                xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
                                 new ActiveXObject("Msxml2.XMLHTTP");

                if (xmlHttpRequest == null)
                return;

                xmlHttpRequest.open("GET", "pick.js", false);
                xmlHttpRequest.send();
                json = eval('('+ xmlHttpRequest.responseText +')');
            }
        </script>
        ......
    </head>

    <body>
        <div data-role="page" id="map-page"> 
            <script type="text/javascript">
                $('#map-page').live('pageinit',function(){
                    initialize();
                });
            </script>
            .....
        </div>
    </body>
</html>
4

1 回答 1

0

由于您使用的是 jQuery Mobile(因此是 jQuery),您应该考虑使用jQuery.ajax——它处理所有“困难的事情”,例如为您创建 XHR 对象。

对于您的情况,您的代码将如下所示:

function initialize() {

   $.get("pick.js", function(data, status, jqXHR) { 
       //when the call succeeds, do something with the 'data' param
       console.log(data);
   }, "script");
}
于 2013-01-31T15:51:22.467 回答