我多次测试以下代码。效果很好,我得到的结果是"返回photoMenu_sb.ToString();"一旦我删除字符串参数photoFileName。但是当我声明并尝试传递字符串photoFileName时没有任何反应。为什么?
我认为问题在于将字符串photoFileName声明并传递给javascript函数但我无法识别问题,因为我没有收到任何错误。在某处有没有遗漏的引文?
[WebMethod]
public static string LoadPhotosPopup(int offset, int fetch, string IDuserInput)
{
StringBuilder photosPopup_sb = new StringBuilder();
var photosPopup_query = db.Query("SELECT IDphoto], [photoFileName] FROM [photos] WHERE ([IDuser] = @0 AND [photoPublished] = 'True') ORDER BY [photoDate] DESC OFFSET @1 ROWS FETCH NEXT @2 ROWS ONLY", IDuserInput, offset, fetch);
foreach (var item in photosPopup_query)
{
var IDphoto = item.IDphoto;
var photoFileName = item.photoFileName;
photosPopup_sb.Append("<img src=\"Images/Design/openmenu.png\" onclick=\"photoMenu(" + IDphoto + ", '" + photoFileName + "') \" />");
}
return photosPopup_sb.ToString();
}
的JavaScript
function photoMenu(IDphoto, photoFileName) {
$.ajax({
type: "POST",
url: "UserControls/photosFunctions.aspx/photoMenu",
data: "{ IDphoto: " + IDphoto + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CommentsMenu" + IDphoto).html(data.d);
}
})
}
[WebMethod]
{ StringBuilder photoMenu_sb = new StringBuilder();
photoMenu_sb.Append("<label>Testing </label>");
return photoMenu_sb.ToString();
}
UPDATE 自公共静态字符串photoMenu(int IDphoto,string photoFileName) 期待2个参数
data: "{ IDphoto: " + IDphoto + "}", in the javascript function should be
data: "{ IDphoto: " + IDphoto + ", photoFileName: '" + photoFileName + "'}",
答案 0 :(得分:1)
尝试创建一个包含javascript函数字符串的字符串变量:
var img = String.Format("<img src='Images/Design/openmenu.png' onclick='photoMenu({0},'{1}')' />", item.IDphoto, item.photoFileName);
photosPopup_sb.Append(img);
在JavaScript中,您还需要为photofileName参数设置json数据属性:
function photoMenu(IDphoto, photoFileName) {
$.ajax({
type: "POST",
url: "UserControls/photosFunctions.aspx/photoMenu",
data: "{ IDphoto: " + IDphoto + ", photoFileName: '" + photoFileName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CommentsMenu" + IDphoto).html(data.d);
}
});
}
答案 1 :(得分:0)
我认为你错过了一个括号&#34;)&#34;:
photosPopup_sb.Append("<img src=\"Images/Design/openmenu.png\" onclick=\"photoMenu(" + IDphoto + ", '" + photoFileName + "')\" />");
答案 2 :(得分:0)
我没有看到photoFileName
的示例值,但如果它有反斜杠,则可能必须确保该字符串已正确转义。
例如:
//causes errors
called(1, 'file\path\img.png');
//successful
called(1, 'file/path/img.png');