views:

300

answers:

1

Hi , I try to call webservice using json , when i call to web service without excepted parameters , its work , but when i'm try to send parameter , ive got an error :

This is my code:

function GetSynchronousJSONResponse(url, postData) 
{

    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    url = url + "?rnd=" + Math.random(); // to be ensure non-cached version

    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    var responseText = xmlhttp.responseText;
    return responseText;
}


function Test() 
{
    var result = GetSynchronousJSONResponse('http://localhost:1517/Mysite/Myservice.asmx/myProc', '{"MyParam":"' + 'test' + '"}');
    result = eval('(' + result + ')');
    alert(result.d);
}

This is the error :

System.InvalidOperationException: Request format is invalid: application/json; charset=utf-8.

at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()

at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest

What is wrong ?

Thanks in advance .

A: 

From what I can tell, your application cannot accept application/json as a post data format. Use application/x-www-form-urlencoded instead and set your JSON to a request parameter that you can then access using Request.Params["key"]:

xmlhttp.open("POST", url, false); 
xmlhttp.setRequestHeader(
    "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"
); 
xmlhttp.send("json="+encodeURIComponent(postData)); 
var responseText = xmlhttp.responseText; 
return responseText; 

Also, as I mentioned in my comment, you can remove the following line:

url = url + "?rnd=" + Math.random(); // to be ensure non-cached version   

POST requests aren't cached and it's generally bad practice to use GET parameters with POST requests.

Andy E