-
Notifications
You must be signed in to change notification settings - Fork 137
Open
Description
代码如下
var demo2 = new Vue({
el: '#demo2',
data: {
a: 1,
},
methods: {
ajax: function() {
var self = this;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText)
console.log(json)
console.log(self.a)
self.a = json.name;
}
}
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
}
}
})
视图如下
{{a}}
<button @click="ajax()">Ajax</button>
这里要注意的是ajax函数里的this是指向demo2对象的,而xmlhttp.onreadystatechange指向的则是自己,所以这里要用var self = this;保留对demo2对象的指向,然后就可以用原生的JS实现ajax的请求了
php代码如下 test.php
<?php
echo json_encode(array('name'=>'wsscat'));
?>
Metadata
Metadata
Assignees
Labels
No labels