JQuery控制器URL拼接问题:接口返回空数组求助
Troubleshooting Empty
monthData Array in AJAX Request for Expiations API Let's break down the issues here step by step—your empty monthData is likely due to a couple of easy-to-fix mistakes:
1. Critical Variable Mix-Up (The Main Culprit)
You stated you want the final URL to be /api/ExpiationsWebAPI?category=01&year=2017, but your variable assignments are reversed:
var yearReturned = 01; // This should be 2017 var categoryReturned = 2017; // This should be 01
This means your constructed URL is actually ?category=2017&year=01—the API is almost certainly returning no data because these parameter values don't match any valid records.
2. Other Potential Issues to Fix
- Undeclared
monthData: You’re assigningmonthData = graphData;without declaring it first, which makes it a global variable (bad practice, and can lead to unexpected behavior). Always declare variables withvar,let, orconst. - Redundant
document.readyNesting:$(function graphDataIn() { ... })is just a shorthand for$(document).ready(), so nesting it inside another$(document).ready()is unnecessary and can delay execution. - Unnecessary
new String:var controlUrl = new String;is overcomplicating things—just initialize it as an empty string or directly build the URL. - Legacy
successCallback: While it works, thesuccessparameter in jQuery AJAX is legacy; modern code uses thedone()method instead.
Corrected Code
Here's the fixed version that addresses all these issues:
// Correct variable assignments (use string for category to preserve leading zero if needed) var categoryReturned = "01"; var yearReturned = 2017; // Directly build the URL without unnecessary initialization var controlUrl = "/api/ExpiationsWebAPI?category=" + categoryReturned + "&year=" + yearReturned; // Proper document ready handler (no nesting) $(document).ready(function () { // Declare monthData in the correct scope let monthData = []; function graphDataIn() { $.ajax({ type: "GET", url: controlUrl, dataType: "json" // Explicitly request JSON to avoid parsing issues }) .done(function (graphData) { console.log("Graph Data loaded", graphData); monthData = graphData; alert("Success"); }) .fail(function (xhr, status, error) { // Log error details for easier debugging console.error("AJAX Failed:", status, error); alert("Fail: " + error); }) .always(function () { alert("Complete"); }); } // Call the function to trigger the request graphDataIn(); });
Quick Debugging Tip
Add console.log(controlUrl); right after building the URL to verify it matches your expected format before sending the request—this will catch variable mix-ups instantly.
内容的提问来源于stack exchange,提问作者Steven Hale
相关产品推荐
相关产品推荐

