xml_http.onreadystatechange不是一个函数

时间:2016-08-25 09:56:10

标签: javascript ajax

我正在尝试克服ajax请求,但Chrome控制台向我显示以下消息: xml_http.onreadystatechange不是函数

这是我的JS代码:

function ajax_request () {
            var xml_http = new XMLHttpRequest();

            xml_http.onreadystatechange(function () {
                if(xml_http.readyState == 4 && xml_http.status == 200){
                    var result = document.getElementById('result');
                    result.innerHTML = xml_http.responseText;
                }
            });
            xml_http.open('GET', 'data.php', true);
            xml_http.send();
        }

这是HTML:

<button onclick="ajax_request();">Click</button>
    <div id="result"></div>

3 个答案:

答案 0 :(得分:0)

您必须为onreadystatechange分配一个函数,而不是将其作为函数调用,而将另一个函数作为参数传递。

xml_http.onreadystatechange = function () { ... };

答案 1 :(得分:0)

你能试试吗

        Office.initialize = function (reason) {
            $(document).ready(function () {
                if (! Office.context.requirements.isSetSupported('WordApi', 1.1)){
                    $.blockUI({message: "This Add-In only works with versions of Office 365 greater than 16, please ring the help doesk to get your version upgraded <br/><a href='https://www.office.com/1?auth=2&home=1&from=ShellLogo'><u>Or click here for Office 365</u></a>"});
                }
                else {
                    // If setSelectedDataAsync method is supported by the host application
                    // the UI buttons are hooked up to call the method else the buttons are removed     
                    if (Office.context.document.setSelectedDataAsync) {             
                        ExecuteOrDelayUntilScriptLoaded(addDocsAsYouGo, "sp.js");   
                        ExecuteOrDelayUntilScriptLoaded(addDocsAsYouGoDefr, "sp.js");
                        if(!siteInitialised){
                            initialiseSharePointConnection();
                        }
                        if (!pathInitiliased){
                            clientContext.executeQueryAsync(function () {           
                                filePath = oWebsite.get_serverRelativeUrl() + "/Shared Documents/addin/ContentDOCX/";
                                pathInitiliased = true;             
                            });
                        }
                    }       
                }
            });
        };

答案 2 :(得分:0)

xml_http.onreadystatechange=function () {
            if(xml_http.readyState == 4 && xml_http.status == 200){
                var result = document.getElementById('result');
                result_data = JSON.parse(xhr.responseText)
                result.innerHTML = result_data;
            }
        }

您必须先解析 JSON 数据才能使用。