【发布时间】:2016-02-03 14:09:39
【问题描述】:
我在 html 页面中使用 Jquery ajax 将数据发布到 WebaPi 控制器时遇到问题。当我通过 fiddler 进行测试时,它已连接并且工作正常,但是当我尝试使用 Ajax 时它只给出错误..
这是我的示例代码..
var bookData = {
"CurrentCompany": "BizSight Sample Product Company",
"CompanyName": CompanyName,
"LegalName": "Biztech",
"Address1": Address1,
"Address2": Address2,
"City": City,
"State": State,
"Phone": Phone,
"ZipCode": ZipCode,
"Fax": Fax,
"Email": Email,
"Website": Website,
"CountryID": 1,
"federalTaxID": 1,
"CurrentUser": CurrentUser,
"BusinessType": BusinessType,
"CurrentFiscalYear": Jsondate
};
$.ajax({
type: "POST",
cache: false,
url: "http://77b2130d5c3446eea4e4210c51529230.cloudapp.net:8080/Create/",
data: JSON.stringify(bookData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
var result = JSON.stringify(data);
$("#loading").show();
alert("success..." + result);
},
error: function (xhr) {
$("#loading").show();
alert("Test3:" + xhr.statusText);
}
});
当我从 html 发布数据并检查提琴手时,它会给出如下图所示的消息
我在这段代码中遗漏了什么..?提琴手它自己在工作,但 frmo html 页面不工作..你能帮我解决和实现这个
我的 Api 类 `
public class CreateController : ApiController
{
public static string CompanyName = " ";
public static string con;
public static string sqlConnection;
public static string DatabaseName;
string TrustedConnection = "Yes";
string DBServer = " ";
string FilePath = null;
string testFirstline = " ";
//clsLog objLog = new clsLog();
bool isSuccess = false;
public string Post(DatabaseCls cls)
{
string ReturnMessage = "Success";
// ReturnMessage = "Hello " + id + "_" + parameter1 + "_" + parameter2 + "_" + parameter3 + "_" + parameter4 + "_" + parameter5 + "_" + parameter6 + "_" + parameter7 + "_" + parameter8 + "_" + parameter9 + "_" + parameter10 + "_" + parameter11 + "_" + parameter12 + "_" + parameter13 + "_" + parameter14 + "_" + parameter15;
return ReturnMessage;
}}
谢谢 维克多.A
【问题讨论】:
-
你确定你需要这样做吗:
data : JSON.stringify(bookData), -
你能显示你得到的错误、webAPI 方法和你试图序列化的类吗?如果在从 ajax 调用该方法时找到该方法但您收到错误,那么您的对象很可能不会序列化为您指定的类型,或者您的 webAPI 尚未设置为允许 CORS 请求。
-
@timothy,我需要将 json 数据传递给我的 api .. 是否有任何替代 ..?
-
@Stephen ,除了错误字符串之外,它不提供任何消息.....但是当我测试提琴手 post 方法成为 Option ..
-
好的,您看到的选项错误是我所指的 CORS 问题,您的 API 必须设置为允许跨站点请求。
标签: c# jquery ajax html asp.net-web-api