我尝试使用两个参数向服务器发出ajax请求,并从服务器字符串中获取:
JavaScript的:
function getLetterOfResponsibilityNote(selectedCountryCode, selectedIntendedUseType) {
$.ajax({
type: "POST",
url: "/Admin/Applications/SelectLetterOfRespinsibilityNote",
cache: false,
data: { countryCode: selectedCountryCode, intendedUseType: selectedIntendedUseType },
success: function(response) {
if (response !== "") {
alert("1");
}
}
});
}
和mvc行动:
[HttpPost]
public string SelectLetterOfRespinsibilityNote(string countryCode, string intendedUseType)
{
var countryDetails = new List<ContryLetterOfResponsibility>
{
new ContryLetterOfResponsibility
{
CountryCode = countryCode,
IntendedUseType = intendedUseType
}
};
string xml = XmlSerializerUtil(countryDetails);
var country = _countryService.GetLetterOfResponsibilityNotesByCountryCodeList(xml).FirstOrDefault();
if (country != null)
{
return country.LetterOfResponsibilityNote;
}
return string.Empty;
}
我在javascript中获取response
个对象并验证其值。如果它的值不是空字符串,我得到警报消息。如果服务器传入JavaScript空字符串,我在成功操作中得到Document object
NOT EMPTY STRING。它是什么?
答案 0 :(得分:2)
来自ajax调用的响应是一个对象,而不是一个字符串。要获取字符串,需要使用responseText属性。试试这个:
if (response.responseText !== "")
如果您使用的是jQuery,请see this page了解更多详情。
答案 1 :(得分:0)
success函数传递一个参数,该类型的类型基于发送到.ajax调用的数据类型属性,或者是从返回的数据推断出来的。因此,您可能希望尝试在ajax对象中显式设置数据类型:“text”,这应该强制响应变量为字符串:
function getLetterOfResponsibilityNote(selectedCountryCode, selectedIntendedUseType) {
$.ajax({
datatype: "text", // <-- added
type: "POST",
url: "/Admin/Applications/SelectLetterOfRespinsibilityNote",
cache: false,
data: { countryCode: selectedCountryCode, intendedUseType: selectedIntendedUseType },
success: function(response) {
if (response !== "") {
alert("1");
}
}
});
}