2012-05-30 72 views
1

我想用一個參數從javascript調用url,然後url必須爲該特定請求提供響應。如何從JavaScript調用一個url並獲得從url到JavaScript的響應?

的反應居然是這樣的:

{"success":true, 
"result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireTime":1338372183} 
} 

,如果我直接嘗試的網址,瀏覽器,我可以得到相同的響應easily.but通過JavaScript的它不工作。

我已經發布了我的示例代碼用於測試目的,但沒有任何迴應。

那麼請幫助我如何打電話並獲得迴應?

在此先感謝。

<html> 
    <head> 
     <script type="text/javascript"> 
      function getResponse() 
      { 
       var uname=document.testform.uname.value; 

       $.ajax({ 
       type: 'POST', 
       url: 'http://192.168.2.113/crm/webservice.php?operation=getchallenge&username='+uname, 
       data: {}, 
       dataType: 'json', 
       success: function(data) 
       { alert('got here with data'); }, 
       error: function() { alert('something bad happened'); } 
       }); 

      } 
     </script> 
     <title>Test</title> 
    </head> 
    <body> 
     <form name="testform" method="post"> 
      <div id="main" border="5" style="width:100%; height:100%;"> 
       <div id="sub" style="width:50%; height:50%;align:center;"> 
        Username:<input type="text" name="uname"> 
        <input type="button" name="ok" value="submit" onclick="getResponse();"> 
       </div> 
      </div> 
     </form> 
    </body> 
</html> 

回答

0

你不包括jQuery庫...

這個加入的<head>頂部:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 

如果您檢查控制檯錯誤,你會看到$ ISN」定義。

0

data param你傳遞給success函數包含你的響應,當你返回JSON時,很容易訪問任何部分。

// (inside your ajax call) 
success: function(data) { 
    alert(data.result.token); 
    alert(data.result.serverTime); 
    alert(data.result.expireTime); 
}, 
+0

嗨,我有插入jQuery庫,並添加您上面的代碼也。 – cheliyan

+0

但是,我得到了錯誤響應only..it正在像[對象對象] – cheliyan

+0

也看到一些勝利的答案在跨域,如果你的ajax是錯誤的,那就是爲什麼,但我的代碼是你會用什麼來獲得數據輸出。如果你有螢火蟲,請嘗試使用'console.log()'而不是'alert()'來公開對象內容。 – Dunhamzzz

2

gdoron說你忘記在代碼中包含jQuery的一個原因。但最主要的是你正在使用與域名交叉的Ajax,那就是問題所在。如果您在瀏覽器中輸入網址,它會正常工作,因爲它會直接從瀏覽器向網站請求。但是你不能使用ajax發送這樣的請求跨域。

我建議你看看JSONP或ajax跨域,如果你想從不同的網站獲取數據。

0

這可能會幫助您:

<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 

</head> 
<body> 

<div id="div1" hidden="true"> </div> 

<button>Get External Content</button> 



<script> 
    $("#div1").load('http://192.168.2.113/crm/webservice.php?operation=getchallenge&username='+uname); 

    $(document).ready(function(){ 
     $("button").click(function(){ 
      var t=$("#div1").text(); 
      alert(t); 

     }); 
    }); 

</script> 
</body> 
</html>