I have the following code in C# that I'm able to attach to IE, and it runs through fine until I hit the JSON, which I receive a javascript error complaining about the syntax. How exactly should I escape javscript code within C# ?

                string jsonStr = @"[ 
                                     { \'name\': \'Obj1\', \'description\': \'Test description...\', \'url\':\'http://www.test.com\' },
                                     { \'name\': \'Obj2\', \'description\': \'Testing...\', \'url\':\'http://www.test.com\' },
                                     { \'name\': \'Obj3\', \'description\': \'Welp...\', \'url\':\'http://www.test.com\' }
                                   ]";

                IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
                scriptObject.type = @"text/javascript";
                scriptObject.text = @"function test() { 
                                        var Edit = 'document.getElementById(\'tTest\').innerHTML = \'<h2 class=\'label3\'><span>Foo</span></h2><ol class=\'container-list\'>';
                                        var json = '" + jsonStr + @"';
                                        $.each(json, function (index, x) {
                                                                    Edit += '<li class=\'test1\'><h3><a href=\'#\'><b>' + x.name + '</b> 1</a></h3><div class=\'url\'><cite>' + x.url + '</cite></div><div class=\'creative\'>' + x.description + '</div></li>';
                                        });
                                     Edit += '</ol>\';
                                     eval('Edit');
                                     }";

                ((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);


                IHTMLDocument2 doc = (IHTMLDocument2)this._webBrowser2.Document;
                IHTMLWindow2 parentWindow = doc.parentWindow;
                if (parentWindow != null)
                    parentWindow.execScript("test();", "javascript");

The c# code is fine, I'm just having trouble wrapping my head about injecting the javascript code with all the quotations, single quotes, etc to eliminate the javascript error. Any help is GREATLY appreciated!

有帮助吗?

解决方案

When using verbatim string literals prefixed with @, it means that the enclosed string is treated as literal. So basically no backslash '\' escaping. To escape double quote ("), just double it ("").

string jsonStr = @"[ 
  {""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },
  { ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },
  { ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }
]";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top