当使用.ashx地址得到javascript错误:myxmlhttprequest.open不是一个函数

时间:2011-05-14 14:46:36

标签: javascript xmlhttprequest ashx

我无法访问SayHello.ashx,我收到了这个javascript错误:

  

httpReq.open不是一个函数。

但是当我使用aspx页面来回答xmlhttprequest时,代码工作正常:

httpReq.open("POST", "SayHello.aspx");  
问题在哪里?这问题可以来自我的.ashx文件吗?

function callASHX() {
    var httpReq=XMLHttpRequest();        
    var x = document.getElementById('txtName').value; 
    var sendStr = "user_id=" + x;
    httpReq.open("POST", "SayHello.ashx");        
    httpReq.onreadystatechange = XMLHttpRequestCompleted;
    httpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");      
    httpReq.send(sendStr);       
}

// initialize XMLHttpRequest object
function XMLHttpRequest() {
    var httpReq;
    try {
        // Opera 8.0+, Firefox, Safari
        httpReq = new XMLHttpRequest();
    }
    catch (e) {
        // IEBrowsers
        try {
            httpReq = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                httpReq = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                return false;
            }
        }
    }
    return httpReq;
}

1 个答案:

答案 0 :(得分:0)

您没有指定XMLHttpRequest()的返回对象。

试试这个:

function callASHX() 
{    
    var httpReq =  XMLHttpRequest();        
    ....
    if (httpReq)  //potentially this is 'false'!
    {
       httpReq.open("POST", "SayHello.ashx");  
       ....
    }