我试图通过jQuery ajax将自定义HTML对象从我的ASP 2.0网站发送到我的web服务。但是我无法让它发挥作用。
当我删除ObjectHTML部分时,我的web服务中的所有内容都被正确解析。但是当我添加ObjectHTML部分时出现错误。
是否可以发送自定义JavaScript对象?
function SavePage() {
var rowCount = $('#pageArea div.object').length;
var i = 1;
var objects = "[";
$('.object').each(function(index) {
var objectHtml = new ObjectHTML($(this).html());
objects += "{'ObjectID': " + "'" + $(this).attr('objectid') + "', 'ObjectIndex': '" + $(this).attr('objectindex') + "', 'ObjectHTML': " + objectHtml + "}";
if (i == rowCount)
objects += ""
else
objects += ",";
i++;
});
objects += "]";
alert("{'objects': " + objects + "}");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Folder/ObjectService.asmx/SavePage",
data: "{'objects': " + objects + "}",
dataType: "json",
success:
function(msg) {
alert("Success!");
},
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured: " + errorThrown);
}
});
}
function ObjectHTML(rawHtml) {
this.Html = rawHtml;
}
Webservice代码:
[WebMethod(EnableSession = true)]
public string SavePage(List<PageObject> objects)
{
return "";
}
public class PageObject
{
private string _objectid, _objectindex;
private ObjectHTML _objectHtml;
public string ObjectID
{
get { return _objectid; }
set { _objectid = value; }
}
public string ObjectIndex
{
get { return _objectindex; }
set { _objectindex = value; }
}
public ObjectHTML ObjectHTML
{
get { return _objectHtml; }
set { _objectHtml = value; }
}
}
public class ObjectHTML
{
private string _Html;
public string Html
{
get { return _Html; }
set { _Html = value; }
}
}
答案 0 :(得分:3)
在我看来,您在服务器上的C#类和脚本中的Javascript类之间会有些混淆。
您可以做的一件事是使用JSON.Stringify
为JSOn编码htmlvar myObject = JSON.stringify({
ObjectId: $(this).attr('objectid'),
ObjectIndex: $(this).attr('objectIndex'),
ObjectHtml: $(this).html()
});
这将确保html被编码为有效的JSON