开发者

Problem with passing folder path string to web service function via jQuery.ajax

I need to perform asp.net web-service function call via jQuery and pass asp.net application path to it. That's the way I'm trying to do it (code is located within asp.net page, e.g. aspx file):

    var d = "{'str':'<%=System.DateTime.Now.ToString() %>', 'applicationPath':'<%=GetApplicationPath() %>'}";

    $.ajax({ type: "POST",
        url: "http://localhost/testwebsite/TestWebService.asmx/Test",
        data: d,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        },
        success: function (msg) {

        }
    });

That's what GetApplicationPath method looks like:

protected string GetApplicationPath() 
{
    return HttpUtility.HtmlEncode(Request.PhysicalApplicationPath);
}

And here is a header of web-service function which I'm trying to call:

public void Test(string str, string applicationPath) 

Function call works well, but applicationPath parameter does开发者_如何学编程n't passed correctly. When I debug it I see that backslashes are removed, function gets "C:ProjectsSamplesmytestwebsite" instead of "'C:\Projects\Samples\mytestwebsite\'".

How can I overcome this?


OK give this a shot, I tried it (works on my machine).

protected string GetApplicationPath()
{
    return Request.PhysicalApplicationPath.Replace(@"\", @"\\");
}

Then for the javascript stuff. Here I'm using the JSON JavaScript library to make escaping things easier.

// construct object literal to be JSON-stringified
var d = {
    str: "<%=System.DateTime.Now.ToString() %>",
    applicationPath: "<%=GetApplicationPath() %>"
};

$.ajax({ type: "POST",
    url: "http://localhost/testwebsite/TestWebService.asmx/Test",
    data: JSON.stringify(d),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    error: function (xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
    },
    success: function (msg) {

    }
});


Backslashes need to be escaped in JavaScript. Try doing a replace of "\" with double backslashes "\ \" (minus the space):

protected string GetApplicationPath()  
{ 
    return Request.PhysicalApplicationPath.Replace("\", "\\"); 
}

I don't think you need the HTMLEncode part.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜