我一直试图将 jquery 函数的输出传递到我的 c# 页面代码后面进行一些处理,但我不知道如何正确完成它,但我知道它一定是可能的。
我的Html代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Get Selected Radio Button Value</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
var items = [];
$.each($("input[name]:checked"), function () {
items.push($(this).val());
});
$.ajax({
url: 'WebForm1.aspx/LoadStrings',
method: 'post',
contentType: 'application/json',
data: '{jsonString:' + items + '}',
dataType: 'json',
});
alert("You entered: " + items.join(", "));
});
});
</script>
</head>
<body>
<h4>Please select your gender.</h4>
<p>
<label>
<input type="radio" name="gender" value="male" />Male</label>
<label>
<input type="radio" name="gender" value="female" />Female</label>
<br />
<br />
<label>
<input type="radio" name="address" value="Kingston" />Kingston</label>
<label>
<input type="radio" name="address" value="Saint Catherine" />Saint Catherine</label>
</p>
<button type="button">Get Values</button>
</body>
</html>
请帮我将 'items' var 从 jquery 函数传递到我后面的代码,
[WebMethod]
public static string[] LoadStrings(string[] jsonString) {
}
最佳答案
'{jsonString:' + items + '}'
有错误,由于字符串串联,你会得到一个字符串{jsonString:Hello World,How are you}
,但 JSON 有效字符串必须为 {"jsonString": "Hello World", "How are you"}
。
请使用JSON.stringify创建 JSON 有效字符串 JSON.stringify({jsonString: items})
关于javascript - 从 JQuery 函数获取数组到后面的 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56496687/