jquery - 数据未完成的 JQuery Ajax Post
问题描述
我有以下内容,但由于未显示警报,因此 postdata 似乎存在问题。如何正确创建 postdata 以包含所选选项?
HTML
<select id="reportTypeChosen" onchange="reportType()">
<option value="1">Opt1</option>
<option value="2">Opt2</option>
<option value="3">Opt3</option>
</select>
脚本
function reportType() {
var sel = document.getElementById("reportTypeChosen");
var choosenType = sel.options[sel.selectedIndex].value;
var postdata = "{choice: " + choosenType + "}";
$.post("setreporttype.php", function(postdata, status){
alert("Data: " + data + "\nStatus: " + status);
});
}
这会在控制台中出现错误:未定义数据
我也试过:
function reportType() {
var sel = document.getElementById("reportTypeChosen");
var choosenType = sel.options[sel.selectedIndex].value;
$.post("setreporttype.php", function({choice: choosenType}, status){
alert("Data: " + data + "\nStatus: " + status);
}
这也不起作用,但没有任何错误。
更新: postdata 在不正确的地方。更正版本如下:
function reportType() {
var sel = document.getElementById("reportTypeChosen");
var choosenType = sel.options[sel.selectedIndex].value;
$.post("setreporttype.php", {choice: choosenType}, function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
}
解决方案
您正在使用带有两个参数 URl 和一个成功回调的 post 函数,因此您正在发送一个空帖子(尽管关于您的调试,请更加清楚),然后在回复中查找您要发送的数据从回调。
你可能想要这个:
$.post({my-url}, {data-to-send}, function({data-from-server}){
doStuff(data-from-server)
});
推荐阅读
- android - MotionLayout 中的 Android CustomAttribute 以更改 TextView 中的文本
- visual-studio-2017 - 错误 CS1061“DeviceClient”不包含“SetInputMessageHandlerAsync”的定义
- git - Windows 10 上的 git bash 在尝试推送或拉取 GitHub 时报告“致命:遇到 AggregateException。发生了一个或多个错误”
- javascript - 在 Dygraph 的 Y 轴标签中添加逗号分隔符
- swift - 可选类型“AVCaptureDevice?”的值 必须解包为“AVCaptureDevice”类型的值
- python - 仅在所有元素为 0 的矩阵的第一行和第一列中添加元素
- c++ - 如何测试特定的 C++ 语句是否比其他语句更快或更慢?
- swift - 控制嵌套的 UITabController
- asp.net - vb.net 代码未在 asp.net 页面上运行
- azure-redis-cache - 线程“主”redis.clients.jedis.exceptions.JedisDataException 中的异常:ERR 密码无效