Posting JSON data from a Chrome browser extension to an MVC controller
I've written a Chrome browser extension that uses Ajax to post data to an MVC3 controller. To make sure that the controller code works, I first wrote a Razor 开发者_JAVA百科web page to prototype the ajax code. This code works within the web page, JSON model binding an all. I published it to an IIS7 server complete with DNS host and domain name. The code still works on the test page.
function addUrl()
{
$('#res').html('Adding...');
var myData = { url: $('#urlDiv').html(), comments: $('#c1').val() };
$.ajax(
{
url: 'http://hostname.domainname/ControllerName/AddUrl',
type: "post",
dataType: "json",
data:JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
success: function (result)
{
$('#res').html(result);
},
error: function()
{
$('#res').html('An error occurred');
}
}
);
};
I copied this jQuery function into the Chrome JavaScript file and called it from a pop-up window via a conventional form button.
<body onload="buildPopupDom();">
<form>
<h2>Add URL</h2>
<div id='urlDiv'></div>
<p>Comments<br /><textarea id="c1" cols="80" rows="3"></textarea></p>
<p><input type="button" value="Save" id="s1" onclick="addUrl();" /> <input type="button" value="Close" onclick="javascript:window.close();" /></p>
</form>
For some reason posts from the Chrome extension incur a 404 error and it occurred to me that that some MVC3 XSS protection or similar is blocking the post - or perhaps something in IIS7 (UrlScan is not installed).
In order to make cross domain XHR calls corresponding domain permissions need to be declared in the manifest.
精彩评论