You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JSON配置文件读取服务端地址并配置到AJAX请求中?

How to Move Server URL to a Separate JSON Config and Use It in AJAX Calls

Got it, let's walk through exactly how to pull this off. You'll split your config into a dedicated file, load it, and wire it into your AJAX requests seamlessly—no more hunting through your main code to update the server address.

Step 1: Create a JSON Config File

First, make a new file (let's name it config.json) in your project. This will hold your server URL in a clean, easy-to-edit format:

{
  "rpiUrl": "http://192.168.10.75:1337/"
}

Now you can tweak this URL anytime without touching your core JavaScript—perfect for switching between dev/prod environments or quick fixes.

Step 2: Load the Config File

Next, you need to fetch this config data before making AJAX calls. Since you're using jQuery, we'll use $.getJSON() to load it. You can trigger this when your page initializes, like on document ready:

var RPiService = {};
var RPi_Url; // We'll populate this from the config

// Load config first when the page is ready
$(document).ready(function() {
  $.getJSON('config.json')
    .done(function(config) {
      RPi_Url = config.rpiUrl;
      console.log("Config loaded successfully:", RPi_Url);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      console.error("Failed to load config:", textStatus, errorThrown);
      // Optional: Set a fallback URL if config fails to load
      RPi_Url = "http://default-fallback-url:1337/";
    });
});

If you prefer vanilla JavaScript, you can use fetch() instead:

fetch('config.json')
  .then(response => response.json())
  .then(config => {
    RPi_Url = config.rpiUrl;
  })
  .catch(error => {
    console.error("Config load failed:", error);
    RPi_Url = "http://default-fallback-url:1337/";
  });

Step 3: Update Your AJAX Service

Now modify your RPiService to use the loaded URL. I added a quick check to make sure the config is loaded before making requests—this prevents errors if your app tries to call the service too early:

RPiService = {
    changeDeviceState: function (state) {
        // Guard clause: Make sure config is loaded
        if (!RPi_Url) {
            console.error("Config not loaded yet—waiting or using fallback?");
            // Return a rejected promise to handle this gracefully
            return $.Deferred().reject("Config not loaded").promise();
        }

        var jqXhr = $.ajax({
            url: RPi_Url + "?state=" + state,
            crossDomain: true,
            dataType: "jsonp", // Fixed typo: jQuery uses camelCase for dataType
            success: function (data) {
                console.log(data);
            }
        });
        return jqXhr;
    }
};

Quick note: I fixed a small typo in your original code—datatype should be dataType (jQuery is case-sensitive here).

Bonus: Wait for Config Before Initializing Your App

If your entire app depends on this config, wrap your app setup inside the config's done() callback. This ensures you never try to make requests before the URL is ready:

$(document).ready(function() {
  $.getJSON('config.json')
    .done(function(config) {
      RPi_Url = config.rpiUrl;
      // Initialize your app/service here
      initApp();
    })
    .fail(function() {
      // Show an error message to the user if config fails
      alert("Failed to load server configuration.");
    });
});

function initApp() {
  // Your app setup code goes here—RPi_Url is ready to use
}

That's all! Now your server URL is neatly isolated in a config file, easy to update, and your AJAX calls use it reliably.

内容的提问来源于stack exchange,提问作者zaheer afzal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:58:46