gpt4 book ai didi

c# - 从 jquery ajax 调用 wcf 服务时出现未定义错误

转载 作者:行者123 更新时间:2023-11-30 20:45:13 25 4
gpt4 key购买 nike

我正在尝试从 jquery ajax 调用 WCF 服务,但我只收到未定义的错误。请帮我解决这个问题。我的服务运行良好,但我的问题是从 ajax 调用 WCF。我的代码在这里

$('#customerName').autocomplete({
source: function (request, response) {
var param ={email:$('#customerName').val()};
$.ajax({
url: "http://localhost:53925/Service1.svc/Getusermail/" + $('#customerName').valueOf(),
data:"{}",
dataType: "json",
type: "GET",

processData: true,
async:false,
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown)
{
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err);
//console.log(err.Message);
},
success: function (data)
{
alert("correct code");
//response(data.d);
}
});
},
minLength: 1 //This is the Char length of inputTextBox
});
});

我也在 WCF 的 web.config 中添加了必需的配置。在此先感谢。我的服务代码在这里

public List<string> Getusermail(string email)
{
List<string> emailid = new List<string>();
string query = string.Format("SELECT email FROM nciuser WHERE email LIKE '%{0}%'", email);
//Note: you can configure Connection string in web.config also.
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=mbci;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
emailid.Add(reader.GetString(0));
}
}
}
return emailid;
}

上述方法的接口(interface)是

 [OperationContract(Name = "Getusermail")]
[WebGet(UriTemplate = "Getusermail/{email}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
List<string> Getusermail(string email);

最佳答案

您的代码中有几个错误:

  1. $('#customerName').valueOf() 不返回文本框的值。您应该为此使用 $('#customerName').val()

    更好的是:自动完成小部件在 request 参数中提供值。使用 request.term 而不是直接从元素中读取它。

  2. 删除数据:“{}”。由于这是一个 GET 请求,jQuery 会将数据添加到 URL 的末尾:/Service1.svc/Getuseremail/test?{}

    /li>
  3. 根据配置和版本,WCF 运行时将返回一个带有或不带 d 属性的对象。为了安全起见,您可以使用 response(data.d || data)。这将选择 d 属性(如果存在),否则使用完整对象。

$('#customerName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service1.svc/Getusermail/" + request.term,
dataType: "json",
type: "GET",

processData: true,
async: false,
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
},
success: function (data) {
response(data.d || data);
}
});
},
minLength: 1 //This is the Char length of inputTextBox
});

关于c# - 从 jquery ajax 调用 wcf 服务时出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28447345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com