我有一个HTML表单,一旦调用了JSON数据,我就会填写该数据,我的JSON文件中也有两组数据。
我试图在数据字符串(在这种情况下为参考编号)不正确时显示错误提示,但是,每次我输入参考编号之一时,都会出现错误出现此消息是因为没有调用另一个,有人可以帮助我吗?
这是我的JQuery:
$("#clickme").click(function () {
$.getJSON("insurance.json", function (obj) {
$.each(obj, function (key, value) {
//Makes sure Search matches a reference number
if ($("#search").val() == value.InsuranceReferanceNumber) {
$(".hide").addClass("show");
$(".hide").removeClass("hide");
$(".ins").hide();
// Inputs values into form
$("#firstname").val(value.Firstname);
$("#lastname").val(value.Lastname);
$("#address").val(value.Address);
$("#phone").val(value.PhoneNumber);
$("#dob").val(value.DOB);
$("#email").val(value.Email);
$("#carmanf").val(value.CarManufacturer);
$("#model").val(value.CarModel);
$("#year").val(value.Year);
$("#fuel").val(value.FuelType);
$("#engine").val(value.EngineSize);
$("#cover").val(value.TypeofCover);
$("#bonus").val(value.NoClaimsBonus);
$("#paid").val(value.Paid);
$("#amount").val(value.Amount);
}
else {
alert("Error");
}
});
});
});
这是JSON文件,其中填充了错误的数据。
[{
"InsuranceReferanceNumber": "CAR123"
, "Firstname": "Jerry"
, "Lastname": "Ford"
, "Address": "1 Brick Lane"
, "PhoneNumber": "077123456"
, "DOB": "12/08/1976"
, "Email": "jerry.ford@mail.com"
, "CarManufacturer": "Audi"
, "CarModel": "R8"
, "Year": 2017
, "FuelType": "Diesel"
, "EngineSize": 5.2
, "TypeofCover": "Third Party "
, "NoClaimsBonus": "3 Years"
, "Paid": "Annually"
, "Amount": 1800
}
, {
"InsuranceReferanceNumber": "CAR456"
, "Firstname": "Danny"
, "Lastname": "Beach"
, "Address": "23 Oaklands Dr"
, "PhoneNumber": "077654321"
, "DOB": "09/11/1996"
, "Email": "danny.beach@mail.com"
, "CarManufacturer": "Vauxhall"
, "CarModel": "Corsa"
, "Year": 2011
, "FuelType": "Petrol"
, "EngineSize": 1.2
, "TypeofCover": "Comprehensive"
, "NoClaimsBonus": "2 Years"
, "Paid": "Monthly"
, "Amount": 800
}
]
答案 0 :(得分:0)
我不确定我是否正确理解了您的问题,但我会尽力提供帮助。您在'$ .each'周期内以及
内进行逻辑运算$("#search").val() == value.InsuranceReferanceNumber
不正确,您的代码会触发警报。但是,此代码实际上几乎每次都会显示警报,因此我认为您必须使用以下命令更改代码:
$("#clickme").click(function () {
$.getJSON("insurance.json", function (obj) {
var found=false;
$.each(obj, function (key, value) {
//Makes sure Search matches a reference number
if ($("#search").val() == value.InsuranceReferanceNumber) {
$(".hide").addClass("show");
$(".hide").removeClass("hide");
$(".ins").hide();
// Inputs values into form
$("#firstname").val(value.Firstname);
$("#lastname").val(value.Lastname);
$("#address").val(value.Address);
$("#phone").val(value.PhoneNumber);
$("#dob").val(value.DOB);
$("#email").val(value.Email);
$("#carmanf").val(value.CarManufacturer);
$("#model").val(value.CarModel);
$("#year").val(value.Year);
$("#fuel").val(value.FuelType);
$("#engine").val(value.EngineSize);
$("#cover").val(value.TypeofCover);
$("#bonus").val(value.NoClaimsBonus);
$("#paid").val(value.Paid);
$("#amount").val(value.Amount);
found=true;
return false;
}
});
if(!found)
alert("Error");
});
});