2 回答
TA贡献1798条经验 获得超3个赞
我知道你有解决方案,但我会发布我的答案
第一: echo json_encode
第四:根本不需要使用,x
可以直接使用key
第五:可以直接使用dataType: 'json'
代替JSON.parse(data)
第六:更改.html(
为.append(
考虑以上所有内容,那么您的代码应该如下所示
php
<?php
if(isset($_POST['submit'])){
// Validate results and if correct insert into the DB
// Else add the respective errors
$data['error']['error_1'] = 'Error_1_text'; // change all `$data[0]` to `$data['error']` it will be much easier
$data['error']['error_2'] = 'Error_2_text';
/*
.
.
.
*/
$data['error']['error_n'] = 'Error_n_text';
echo(json_encode($data)); // <<<< just $data here
}
?>
JS
<body>
<div class="ssss"></div>
</body>
<script>
$.ajax({
url: "http://localhost/path/to/above/file",
method: "POST",
dataType : 'json', //<<<<< here
data: {
submit: 'yes',
form_data_0: 'form_text',
form_data_1: 'form_text',
form_data_2: 'form_text'
},
success: function(data){
// Code to check if errors were present
if (data.error) { //<<<<< here
$.each(data.error, function(key, error) {
// Display each error into a modal
$("div#ssss").append('<div id="dmessage_' + key + '" class = "modal" style="display:block"><p id = "pmessage_' + key + '">' + error + '</p></div>');
});
}else{
$("div#ssss").html('');
}
}
});
</script>
TA贡献1853条经验 获得超9个赞
这解决了我的问题:
<script>
$.ajax({
url: "http://localhost/path/to/above/file",
method: "POST",
data: {
submit: 'yes',
form_data_0: 'form_text',
form_data_1: 'form_text',
form_data_2: 'form_text'
},
success: function(data){
// Code to check if errors were present
result = JSON.parse(data);
let x = 0;
if (result.hasOwnProperty('0')) {
$.each(result['0'], function(key, error) {
// Display each error into a modal
$("div#ssss").append('<div id="dmessage_' + x + '" class = "modal" style="display:block"><p id = "pmessage_' + x + '">' + error + '</p></div>');
});
}
}
});
</script>
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报