新手如何使用scriptsharp将Json信息发送到Web服务

时间:2011-10-13 06:54:20

标签: json script#

我修改了示例Demo以尝试发送json对象而不是字符串。该网站将其视为一个值[object]而不是Json文本的字符串。我需要改变什么。

namespace DemoScript {
// [Imported]
// [IgnoreNamespace]
public sealed class Person 
{
    public string FirstName;
    public string LastName;
}

[GlobalMethods]
internal static class HelloPage {

    static HelloPage() {
        // Add script that runs on startup as the script is loaded into
        // the page

        Element helloButton = Document.GetElementById("helloButton");

        Person p = new Person();

        helloButton.AddEventListener("click", delegate(ElementEvent e) {
            InputElement nameTextBox = Document.GetElementById("nameTextBox").As<InputElement>();

            p.FirstName = nameTextBox.Value;
            p.LastName = "Surname";

            XmlHttpRequest xhr = new XmlHttpRequest();
//          xhr.Open(HttpVerb.Get, "/HelloService.ashx?name=" +   nameTextBox.Value.EncodeUriComponent());
            xhr.Open(HttpVerb.Get, "/HelloService.ashx?name=" + p);

            ...
        }
    }
}

如果我传递p.FisrtName,它将按预期工作。

2 个答案:

答案 0 :(得分:1)

您需要先对JSON进行编码。在Script#中,本机JSON映射到System.Serialization.Json,其中包含方法Stringify()Parse()

有关原生JSON的文档:https://developer.mozilla.org/En/Using_native_JSON

对于没有原生JSON的浏览器的支持,您可以包含这个流行的脚本:https://github.com/douglascrockford/JSON-js

答案 1 :(得分:0)

感谢DuckMaestro我现在正在使用它。

以防这对其他初学者有用,代码更改为:

p.FirstName = nameTextBox.Value;
p.LastName = "Surname";
XmlHttpRequest xhr = new XmlHttpRequest();
string text = Json.Stringify(p);
xhr.Open(HttpVerb.Get, "/HelloService.ashx?name=" + text);
相关问题