【发布时间】:2015-10-15 17:32:12
【问题描述】:
net Web API 2。我想将 JSON 字符串发送到我的一个 POST 函数并将 JSON 返回给它。
我的 AJAX:
$("#btnPost").click(function (event) {
var sqlQ = "SELECT TOP 50 LTRIM(RTRIM(REPLACE(OID, ' ', ''))) FROM vwPS_DAT WHERE OID != ''";
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'json',
async: true,
cache: false,
contentType: "application/json",
url: "api/FEB/testJSON/",
data: JSON.stringify({ qString: [sqlQ] }),
success: function (result) {
var obj = jQuery.parseJSON(data);
console.log(obj);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
$("#txtResult").val(err.Message)
}
});
}
控制器:
[HttpPost]
public string testJSON([FromBody]List<string> qString)
{
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, string> outPut = new Dictionary<string, string>();
var strReturn = ser.Serialize(qString);
var strReturn2 = ser.Deserialize<Dictionary<string, string>>(strReturn);
if (strReturn2["qString"] != "")
{
outPut.Add("query", "correct");
return ser.Serialize(outPut);
}
else
{
outPut.Add("query", "incorrect");
return ser.Serialize(outPut);
}
}
APP_开始:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, "application/json"));
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
HTML 页面:
<body>
<div style="text-align:center">
<h2>AJAX JQuery JSON test</h2>
Please enter Value1 : <input type="number" id="txtValue1" min="1" max="100"><br><br>
Please enter Value2 : <input type="number" id="txtValue2" min="1" max="100"><br /><br>
Result from Math API Service : <input type="text" id="txtResult" disabled /><br /><br>
<input type="button" value="POST" id="btnPost">
</div>
按下 POST 按钮时出现的错误是:
POST http://localhost:53157/Web/api/FEB/testJSON/ 404(未找到)
Uncaught SyntaxError: Unexpected token
那么我会遗漏什么,因为它甚至似乎都没有找到该功能?
【问题讨论】:
-
JSON.stringify({ qString: [sqlQ] }) 我认为这可能是个问题
-
如果它不是您的 JSON 文件,请尝试使用
url: "/api/FEB/testJSON/"而不是url: "api/FEB/testJSON/",并在"/"前面加上"/"前缀
标签: jquery asp.net json ajax asp.net-web-api2