javascript值是从PHP函数未定义的

时间:2013-06-19 01:08:21

标签: javascript ajax

这可能有一些我错过的非常明显的答案,但我似乎无法弄明白。 PHP和查询的所有搜索功能都有效。唯一不起作用的是数据未在翻译的文本区域中正确显示。以下是代码。

document.getElementById("translated").innerHTML = xmlhttp.open("GET","ajax-result.php?result="+num,true);

innerHTML部分之后,我添加的任何内容(从文本到html)都会进入正确的位置,但现在上面的代码显示它是undefined

3 个答案:

答案 0 :(得分:1)

xmlhttp.open不返回任何内容 - 这就是为什么你得到“未定义”的原因。阅读http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp,特别注意 xmlhttp.onreadystatechange部分。

更方便的方法是使用 jquery ajax方法:http://api.jquery.com/jQuery.ajax/

答案 1 :(得分:0)

这不是ajax的工作方式。您应该在服务器响应

时调用回调函数

这样的东西
if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
}
// setup callback function
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        if(xmlhttp.responseText == 1){
            document.getElementById("translated").innerHTML = xmlhttp.responseText;
        }
    }
}
xmlhttp.open("GET",'your request to sever',true);

答案 2 :(得分:0)

如果你真的想为自己保留一些头痛,我会熟悉jQuery。

这是一个完整的工作示例,说明您试图完成的工作。

输入和按钮的实现只是为了模拟指定值并调用函数的方法。

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            function runAjax(num) {
                $.ajax({
                    'url': 'ajax-result.php',
                    'type': 'GET', // Can also be 'POST'
                    'data': {
                        'result': num
                    },
                    'success': function(result) {
                        $('#translated').html(result);
                        alert('success!');
                    },
                    'error': function(xhr, status, exception) {
                        alert('failed with status code: ' + status);
                    }
                });
            }

            $(document).ready(function() {
                $('button').click(function() {
                    var $input = $('input');
                    var num = $input.val();
                    runAjax(num);
                });
            });
        </script>

        <input type="text" name="num" value="123" />
        <button type="button">Click Me!</button>
    </body>
</html>