【问题标题】:Sending JSON HTTP Get Request within Javascript File在 Javascript 文件中发送 JSON HTTP Get 请求
【发布时间】:2016-01-20 14:12:35
【问题描述】:

从我的 rails 应用程序的一个 javascript 文件中:我想向我的应用程序发送一个 JSON 请求,该请求返回一个字符串数组,并在一个变量中捕获该返回值。

从应用程序的根:请求的路径是:'/employers/get_unique_employer_names.json'

所以如果我处于开发模式:完整的 url 将是:

http://localhost:3000/employers/get_unique_employer_names.json

类似这样的东西,但它不起作用:

// app/assets/javascripts/application.js 
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).ready(function(){
  var array_of_names = get: '/employers/get_unique_employer_names.json'
});

【问题讨论】:

    标签: javascript ruby-on-rails json


    【解决方案1】:

    我想你已经注入了 jquery

    $.ajax({
      url: "/employers/get_unique_employer_names.json"
    })
    .done(function( data ) {
        console.log("here is you data", data);  
    });
    

    没有 jquery 也一样

    var xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if(xmlhttp.status == 200){               
               console.log("Here is your data", xmlhttp.responseText);
           }           
           else {
               console.log('something else other than 200 was returned');
           }
        }
    }
    
    xmlhttp.open("GET", "/employers/get_unique_employer_names.json", true);
    xmlhttp.send();
    

    打开控制台并检查您的数据

    【讨论】:

    • 感谢您的回答。我想我快到了。请参阅我更新的问题。由于某种原因,它会出现未定义。
    • 是正确的,但是你必须把调试器放在array_employer_names = data;之后如果你放在done回调之外,那么调试器将在请求结果返回之前被调用。 Ajax 请求是异步的,这就是使用done 方法的原因。您可以在此处阅读有关同步/异步请求的信息developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
    • 同时检查检查器中的网络选项卡以调试您的请求是否发送无误
    【解决方案2】:

    array_employer_names 未定义,因为它是在您的 js 文件中定义的,这使得它在控制台中不可见。这是一个范围的事情。

    如果您将其更改为

    ,您将能够在控制台中查看它
    $.ajax({
      url: "/employers/get_unique_employer_names.json"
    })
    .done(function( data ) {
        window.array_employer_names = data
    });
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2016-08-04
      • 2020-11-13
      • 1970-01-01
      相关资源
      最近更新 更多