从经典ASP调用REST API及JavaScript AJAX调用API技术咨询
Hey there! Let's tackle your questions one by one—first we'll review your current JavaScript AJAX setup, then dive into how to call REST APIs from classic ASP, plus common pitfalls to avoid.
First, let's look at your existing AJAX code. Here's what you provided:
$.ajax({ type: 'GET', //contentType: "application/json; charset=utf-8", url: 'http://localhost:51870/api/Home/Get', dataType:'json', success: function (data) { debugger; alert(data); }, error: function (error) { debugger; alert('error; ' + eval(error)); } });
关键优化点:
- ContentType注释是对的:For GET requests, you don't need to set
contentTypebecause there's no request body being sent. Leaving this commented out is correct. - Error handling improvement:Using
eval(error)is risky and won't give you useful error details. Instead, use properties likeerror.responseTextorJSON.stringify(error)to get meaningful info:error: function (error) { debugger; alert('Error: ' + error.status + ' - ' + error.responseText); } - Debugging tip:Instead of
alert(data), useconsole.log(data)to inspect the full JSON object in your browser's dev tools—it's way more helpful than a stringified alert.
后端API注意事项:
Your backend uses [System.Web.Http.HttpGet] (Web API attribute) but returns JsonResult (MVC type). For ASP.NET Web API, it's better to return IHttpActionResult for proper HTTP status code handling:
[System.Web.Http.HttpGet] public IHttpActionResult Get() { List<PieChartValue> lstPieChartValue = new List<PieChartValue>(); // Populate your list here return Ok(lstPieChartValue); // Automatically serializes to JSON }
This ensures the response has the correct application/json content type and proper HTTP status codes (like 200 OK).
Classic ASP doesn't have built-in support for REST calls, but you can use the MSXML2.XMLHTTP object to send HTTP requests. Here are step-by-step implementations for common scenarios:
2.1 GET Request Example
<% Dim xmlHttp Set xmlHttp = Server.CreateObject("MSXML2.XMLHTTP.6.0") ' Use latest version apiUrl = "http://localhost:51870/api/Home/Get" xmlHttp.Open "GET", apiUrl, False ' False = synchronous request xmlHttp.setRequestHeader "Content-Type", "application/json; charset=utf-8" xmlHttp.send ' Check response status If xmlHttp.Status = 200 Then ' Get JSON response jsonResponse = xmlHttp.ResponseText Response.Write "Success: " & jsonResponse Else Response.Write "Error: Status " & xmlHttp.Status & " - " & xmlHttp.StatusText End If Set xmlHttp = Nothing %>
2.2 POST Request Example (Sending JSON)
<% Dim xmlHttp, postData Set xmlHttp = Server.CreateObject("MSXML2.XMLHTTP.6.0") apiUrl = "http://your-api-url/post-endpoint" postData = "{""key"": ""value"", ""anotherKey"": 123}" ' JSON payload xmlHttp.Open "POST", apiUrl, False xmlHttp.setRequestHeader "Content-Type", "application/json; charset=utf-8" xmlHttp.send postData If xmlHttp.Status = 200 Then Response.Write "POST Success: " & xmlHttp.ResponseText Else Response.Write "POST Error: " & xmlHttp.Status & " - " & xmlHttp.StatusText End If Set xmlHttp = Nothing %>
常见问题与解决方法
- JSON Parsing in Classic ASP:Classic ASP doesn't have native JSON parsing. To work with the JSON response, you can include a trusted VBScript JSON parsing script (like the widely used json2.js port for VBScript) to safely parse the response text into usable objects. Avoid using raw
eval()unless you fully trust the API's output. - Cross-Domain Requests:If your classic ASP app is on a different domain than the API, frontend calls would hit CORS restrictions—but server-side calls (like the examples above) aren't subject to this. This approach avoids cross-domain issues entirely.
- XMLHTTP Version:Always use the latest version (
MSXML2.XMLHTTP.6.0) instead of older variants to avoid compatibility and security issues. - Encoding Issues:Make sure your classic ASP page uses
<%@ Language="VBScript" CodePage="65001" %>(UTF-8) to match the API's charset, and double-check that theContent-Typeheader is set correctly in your requests.
内容的提问来源于stack exchange,提问作者Aakash Patel

