I am using an MVC approach here. In my javascript code, under the success function.. when I use the code, my expected result comes up. 代码时,出现了我的预期结果。
But when I use the .. the output is TypeError: "".data is undefined from the console.. ..时,输出为TypeError:“” .data在控制台中未定义 。
And if I use ... There is no output in the console.. ...控制台中没有输出。
I expect the result to show in the text field having the id of res.
Here is the html code
<form action="" method="post">
<input type="text" id="uname">
<input type="submit" id="submit">
<input type="text" id="res">
</form>
Here is the javascript code
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'ajax/checkLogin',
dataType : 'json',
data: {
uname : $('#uname').val(),
},
success : function(data){
$('#res').text("".data.msg);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error");
}
});
return false;
});
});
And here is the method code of the controller named Ajax
public function checkLogin()
{
$return['error'] = false;
while (true) {
if (empty($_POST['uname'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you username.';
break;
}
if ($_POST['uname'] == "tin") {
$return['msg'] = 'successful';
break;
}else{
$return['error'] = true;
$return['msg'] = 'Wrong username:'.$_POST['uname'];
break;
}
break;
}
echo json_encode($return);
}
您不需要在data
之前加dot
,您可能不需要将空字符串与数据连接。
$('#res').text(data.msg);
$('#res').text("".data.msg);
change this to
$('#res').text(data.msg);
It is quite clear from the error. TypeError: "".data is undefined. Since string doesn't have a property data
You are trying to concatenate string in javascript with the PHP operator. To concatenate two strings, you have to use the + operator not the . operator
如果您想要空字符串,请用+
而不是进行连接.
$('#res').text(""+data.msg);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.