我们有一个可以嵌套在某个页面中的小部件。在小部件中,我们使用MVC控制器,我们通过以下方式调用Web服务:
public JsonpResult GetAllCities()
{
List<string> allCities = MobileServiceClient.GetAllCities().ToList();
return Jsonp(allCities);
}
如您所见,我们返回JsonpResult。
该服务如下所示:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public List<string> GetAllCities()
{
var connection = ConnectionManager.Instance.CreateConnection();
var sql = string.Format("select distinct CityName from V_Cashdesk where CityName is not null");
var table = DB.GetSQLCached(sql, connection, 5);
var lstCities = new List<string>();
if (table != null)
{
for (var i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i]["CityName"].ToString() != "")
{
lstCities.Add(table.Rows[i]["CityName"].ToString());
}
}
}
return lstCities;
}
但是,当我们调用控制器的GetAllCities方法时,对话框中会出现“parseerror”。
错误是:
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'site_name' is therefore not allowed access.
XMLHttpRequest cannot load site_name/widget/Search/GetAllCities. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'site_name' is therefore not allowed access.
我们怎样摆脱这个?