2012-07-03 106 views
1

我正在练习编码jQuery和Ajax,并制作一个普通的谷歌搜索框,但它不会工作。没有控制台错误,并且在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> 

这段代码有什么问题?

+0

http://en.wikipedia.org/wiki/JSONP –

回答

2

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

此外,您甚至没有交出您的输入字段的值。你应该把它附加到像这样的网址?q=hello

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

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

看看Google Search API

+0

如果您确实需要更具体的页面,请使用实际数据而不是重定向,例如http://www.google.com/search?q = hello',那么你会看到Cross-Origin错误。 – TheZ