0

我正在尝试将 json 消息从自定义应用程序发送到网页。正在返回 json 消息,并且似乎是有效的,但它不会导致成功函数触发。我目前正在使用 jquery-1.4.4.js,之前我使用的是 jquery.com 上托管的 jquery-latest.js。使用该版本我收到“parseerror”错误,但在 1.4.4 中我没有收到成功或失败。

我的代码如下:

在网页上:

<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>

我收到的 json 消息(在 Chrome 的网络面板中查看)

[{"name":"John"},{"name":"Mike"}]

在我的 C# 应用程序中,代码是:

string response = "[{\"name\":\"John\"},{\"name\":\"Mike\"}]";

request.ContentType = "application/json";
webserver.SendToBrowser(response, request);

和 ..

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();
    }

非常感谢任何帮助!

4

1 回答 1

0

JSONP 并不神奇。

您的服务器需要遵循 JSONP 协议并读取callback=参数。

于 2012-07-05T15:43:13.437 回答