谷歌搜索框无法正常工作,没有控制台错误

时间:2012-07-03 15:44:58

标签: html ajax jquery

我正在练习编写jQuery和Ajax并制作一个普通的Google搜索框,但它无法正常工作。没有控制台错误,Chrome中的调试也无济于事。这是代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">

</script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#button").click(function() {
            $.ajax({
                url : "http://www.google.com/search",
                dataType : "html",
                success : function(data) {
                    $("#show").html(data)
                },
                fail : function() {
                    alert("failed lol")
                }
            })
        })
    })
</script>
</head>
<body>
    <div id="search">
        <form name="input" method="get">
            Google it: <input type="text" name="googleit" /> <br /> <br /> <input
                id="button" type="button" value="let me google that for you" />
        </form>
    </div>
    <div id="show"></div>
</body>
</html>

这段代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

您无法轻松进行跨域调用,受Same Origin Policy限制。检查您的网络选项卡,它应该声明请求失败。

此外,您甚至没有移交输入字段的值。您应该将其附加到网址?q=hello

        $.ajax({
            url : "http://www.google.com/search?q=" + $("input").val(),
            dataType : "html",

您需要一个所谓的JSONP-call来访问其他域。

查看Google Search API