【问题标题】:How to retrieve JSON data from server using jQuery?如何使用 jQuery 从服务器检索 JSON 数据?
【发布时间】:2016-05-30 15:45:23
【问题描述】:

我尝试了这个源的几种组合,但我是 jQuery 新手,我找不到我能理解的基本教程。

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery.js"></script>
    </head>
    <body>
        <script>
        var sourceText = "car";
        var transText = "";
        $.getJSON("http://www.worldlingo.com/S000.1/api?wl_password=secret&wl_srclang=EN&wl_trglang=IT&wl_text=" + sourceText,
                function(data){
                  alert("Data: " + data);
                    }).error(function(jqXHR, textStatus, errorThrown){
                            console.log("ERR: %o" , jqXHR);
                            console.log("Result: %s" , jqXHR.responseText);
                            transText=jqXHR.responseText;
                            alert("Translation JSON data provided for '" + sourceText + "': '" + transText + "'");
                    })
        </script>
    </body>
</html>

我只想得到一个单词的翻译。

为什么我得到的翻译是错误而不是结果?

如果实际成功接收到数据,为什么执行永远不会到达警报(数据)?

编辑: 最终答案是:服务器没有提供 JSON 响应,因此上面的源工作正常,由于收到错误的 MIME 类型而触发错误。

【问题讨论】:

  • 如果您看到浏览器控制台,您应该会看到一些错误,例如 XMLHttpRequest cannot load http://www.worldlingo.com/S000.1/api?wl_password=secret&amp;wl_srclang=EN&amp;wl_trglang=IT&amp;wl_text=car. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '....' is therefore not allowed access.
  • 你问题的标题其实和你的问题无关。请解决这个问题。
  • @Arun P Johny :我没有看到任何错误......这就是重点!确实,脚本成功地从服务器获取了结果!我还尝试注释掉“.error”部分:Chrome 控制台中仍然没有错误。
  • 我在 FireFox 中收到此错误:跨源请求被阻止:同源策略不允许读取位于 worldlingo.com/S000.1/… 的远程资源。这可以通过将资源移动到同一个域或启用 CORS 来解决 所以我应该启用这个“CORS”......怎么样?!?为什么 chrome 不抱怨它并实际接收数据但触发错误,就像它没有一样?
  • 解决方案:我使用的服务器没有提供 JSON 格式的数据!出于未知的原因(例如,我正在寻找提供 JSON 格式翻译的服务器......)我认为它确实做到了!

标签: jquery json


【解决方案1】:

看看我在 web 服务上的用途,它会返回你的 json 数据。

您的网络服务可能有错误,或者您在代码中做错了什么。

请检查您的服务器端是否有错误。

希望对你有帮助

 var sourceText = "car";
 var transText = "";
 $.getJSON("http://jsonplaceholder.typicode.com/posts/1",
   function(data) {
     alert("Data: " + data);
   }).error(function(jqXHR, textStatus, errorThrown) {
   console.log("ERR: %o", jqXHR);
   console.log("Result: %s", jqXHR.responseText);
   transText = jqXHR.responseText;
   alert("Translation JSON data provided for '" + sourceText + "': '" + transText + "'");
 })
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    把你的代码放在try catch之间,可能会抛出一些错误。

    try {
      /* YOUR CODE */
    }
    catch(error) {
        console.log(error.message);
    }
    

    【讨论】:

      【解决方案3】:

      我使用的服务器实际上并不是以 JSON 格式提供结果,而是以纯文本格式提供结果,因此不需要 $.getJSON()。

      此外,要使用的正确 URL 是: http://www.worldlingo.com/S000.1/api?wl_password=secret&wl_srclang=EN&wl_trglang=IT&wl_text=WORD_TO_TRANSLATE&wl_errorstyle=1

      最后一个参数将阻止服务器在结果中提供“错误代码”,成功请求为 0,而是写入 HTML 标头。

      我的最终来源是:

      <!DOCTYPE html>
      <html>
          <head>
              <script src="jquery.js"></script>
              <script>
            function myCall() {
               // Status text:
               document.getElementById('progress').innerText="Please wait..."; 
      
                  // URL of your favourite online translation API (Google is no more free):
                  var URL= "http://www.worldlingo.com/S000.1/api?wl_errorstyle=1&wl_password=secret&wl_srclang=EN&wl_trglang=IT&wl_text=";
      
               // Read text to translate:
                  sourceText = document.getElementById('source').value; 
      
                  // Call  translator
                  var jqxhr = $.get(URL + sourceText, function() {
                      document.getElementById('result').innerText=jqxhr.responseText;
                  document.getElementById('progress').innerText="Done.";
                  })
                  .done(function() {
                   // alert( "Finished." );
                  })
                  .fail(function(a,b,c) {
                    alert( "An error occurred while contacting server '" + URL + "': '" + c + "'");
                  });
      }
      </script>
          </head>
          <body>
          <textarea id="source">Write your word here</textarea><br>
          <textarea id="result">Translation will appear here</textarea><br>
          <input type="submit" value="translate" onclick="javascript:myCall()"><span id="progress">-</span><br>
          </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多