使用ajax获取数据并更新表单字段

时间:2014-10-15 01:14:26

标签: php jquery ajax

我在头脑中添加了这段代码:

<script>
function cpf(pag) {
    request = createRequest();
    if(request == null) {
        alert("Unable to Create Request");
        return;
    }
    var nocache = new Date();
    var url = "https://pathto.com/cp/gettime.php?t="+pag;
    url = url + "&stopIEcache="+ nocache;
    request.open("GET",url,true);
    request.onreadystatechange = showtpage;
    request.send(null);
}

function showtpage() {
    if(request.readyState == 4) {
        if(request.status == 200) {
            detailDiv = document.getElementByName("newtdf")[0];
            detailDiv.innerHTML = request.responseText;
        }
    }
}

function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (tryMS) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }
    return request;
}

</script>

以下是我的HTML输出:

<input type="text" value="2014/10/10 05:08" id="datetimepicker" name="newtd" onBlur="cpf(document.getElementByName('newtd')[0].value);" /><br />
Epoch Timestamp Built: <input type="text" name="newtdf" size="10" value="">

所以我有第一个可由datetimepicker选择的字段,当它们离开字段(onblur)时,它应该运行我在脚本上创建的cpf函数,并将字段的值传递给它。

但它没有用。

我运行它并使用调试器,它说:

Uncaught TypeError: undefined is not a function
你可以帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

尝试之前声明请求变量,如下面的代码:

<script>
var request;
function cpf(pag) {
    request = createRequest();
    if(request == null) {
        alert("Unable to Create Request");
        return;
    }
    var nocache = new Date();
    var url = "https://pathto.com/cp/gettime.php?t="+pag;
    url = url + "&stopIEcache="+ nocache;
    request.open("GET",url,true);
    request.onreadystatechange = showtpage;
    request.send(null);
}

function showtpage() {
    if(request.readyState == 4) {
        if(request.status == 200) {
            detailDiv = document.getElementByName("newtdf")[0];
            detailDiv.innerHTML = request.responseText;
        }
    }
}

function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (tryMS) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }
    return request;
}

</script>