I am attempting to send a json message from a custom application to a web page. The json message is being returned, and appears to be valid, but it is not causing the success function to trigger. I am currently using jquery-1.4.4.js, previously I was using jquery-latest.js as hosted on jquery.com. Using that version I received an error of “parseerror”, but with 1.4.4 i don’t receive a success or failure.
My code is as follows:
On the web page:
<script>
$(document).ready(function () {
$.ajax({url: "http://localhost:8080/callback=?",
dataType: "json",
success: function(data)
{
alert("reply received");
},
error: function(data, error)
{
alert("error: " + error);
}
});
});
</script>
The json message I am receiving back (as viewed in Chrome’s network panel)
[{"name":"John"},{"name":"Mike"}]
And in my C# application the code is:
string response = "[{\"name\":\"John\"},{\"name\":\"Mike\"}]";
request.ContentType = "application/json";
webserver.SendToBrowser(response, request);
and ..
public void SendToBrowser(string data, Classes.HTTPRequest request)
{
int numBytes = 0;
byte[] bData = Encoding.ASCII.GetBytes(data);
try
{
string header = "";
header += "HTTP/1.1 200 OK\r\n";
header += "Server: MyServer\r\n";
header += "Content-Length: " + bData.Length.ToString() + "\r\n";
header += "Content-Language: en\n\r";
header += "Content-Type: " + request.ContentType + "\r\n";
header += "Connection: close\r\n\r\n";
Byte[] headerBytes = Encoding.ASCII.GetBytes(header);
if (request.Socket.Connected)
{
request.Socket.Send(headerBytes, headerBytes.Length, 0);
if ((numBytes = request.Socket.Send(bData, bData.Length, 0)) == -1)
Console.WriteLine("Socket Error cannot Send Packet");
else
{
Console.WriteLine("No. of bytes sent {0}", numBytes);
}
}
else
Console.WriteLine("Connection Dropped....");
}
catch (Exception e)
{
Console.WriteLine("Error Occurred : {0} ", e );
}
request.Socket.Close();
}
Any help much appreciated!
JSONP is not magic.
Your server needs to follow the JSONP protocol and read the
callback=parameter.