我正在使用WCF服务从我的jQueryMobile应用程序获取数据并将数据发布到数据库。请注意我的服务在另一台服务器上。我能够从远程服务获取数据。但我在使用POST方法更新数据时遇到问题。以下是我的代码,请帮我找到解决方案。
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="content">
<input name="text-1" id="text1" value="" type="text">
<input name="text-2" id="text2" value="" type="text">
<a href="#" data-role="button" id="useJSONP">Update</a>
</div>
<script type="text/javascript" charset="utf-8">
$(document).on('pagebeforeshow', '#index', function () {
$("#useJSONP").click(function () {
var id = $("#text1").val();
var name = $("#text2").val();
var userData = { "EmployeeID": id, "FirstName": name };
$.ajax({
url: "http://Mysite:83/FromDBDataService.svc/PostEmployeeData?callback=?",
type: "POST",
data: userData,
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata: true,
success: function res(msg) {
alert("hello" + msg);
},
error: function error(response) {
alert("error");
}
});
});
});
</script>
</div>
</body>
</html>
WCF服务: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;
using System.Reflection;
namespace ServiceSite
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class FromDBDataService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public void PostEmployeeData(int EmployeeID,string FirstName)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("update Employees set FirstName=@FirstName where EmployeeID=@EmployeeID", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("@EmployeeID", EmployeeID));
cmd.Parameters.Add(new SqlParameter("@FirstName", FirstName));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
public class EmployeeNew
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
谢谢, Bavya。
答案 0 :(得分:0)
您将无法进行跨域POST请求。您可能感兴趣some hacks。another link
我还建议您详细了解same origin policies。
JSONP请求是通过将脚本放在<script></script>
内来执行的,而不是POST请求。