当下拉列表的值发生变化时,我需要根据下拉列表的新值更改两个文本框的值,而不刷新页面。
这应该很容易,但我无法弄清楚是什么让AJAX嘀嗒。我似乎能够获得价值,但我无法设置文本框。
JavaScript的:
// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
var newDob;
$.ajax({
url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
type: "GET",
success: function (result) {
// Displays correct result
alert(result);
newDob = result;
},
error: function (xhr, status, err) {
alert(err);
}
});
// Causes the box to become blank, HTML value attribute doesn't change
$("#DoB").val(newDob);
});
控制器:
[HttpGet]
public string PatientDob(int patientId)
{
return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}
答案 0 :(得分:1)
尝试在成功函数中保留 $(“#DoB”)。val(result); ,看看它是否有效。
注意:$(“#DoB”)。val(newDob);被修改为$(“#DoB”)。val(result);
答案 1 :(得分:1)
[HttpPost]
public ActionResult Index(DropDownViewModel viewModel)
{
var id = viewModel.SelectedSongId;
...
}
调用是异步的,这意味着在发出AJAX请求之前,您的$.ajax
调用正在执行。需要在AJAX成功回调中完成更改。
$("#DoB").val(newDob);
答案 2 :(得分:0)
问题是默认情况下ajax是异步的,因此代码示例中的las行可能在从服务器获取结果之前执行。
你可以在你的ajax调用中添加async: false
,以便在执行下一个javascript步骤之前等待结果:
$.ajax({
url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
async: false,
type: "GET",
success: function (result) {
// Displays correct result
alert(result);
newDob = result;
},
error: function (xhr, status, err) {
alert(err);
}
});
$("#DoB").val(newDob);
或(最好)在调用的成功方法中设置文本字段(当你等待服务器结果时,这不会阻止执行任何其他代码):
$.ajax({
url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
async: true,
type: "GET",
success: function (result) {
// Displays correct result
alert(result);
newDob = result;
$("#DoB").val(newDob);
},
error: function (xhr, status, err) {
alert(err);
}
});
答案 3 :(得分:0)
尝试这样做。请检查文本框是纯HTML输入还是任何插件生成的文本框。如果是第二个,你必须检查插件以刷新新内容。
// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
var newDob;
$.ajax({
url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
type: "GET",
success: function (result) {
// Displays correct result
$("#DoB").val(result);
},
error: function (xhr, status, err) {
alert(err);
}
});
// Causes the box to become blank, HTML value attribute doesn't change
});