我有Knockout For Students预订,并关注AJAX:
self.loadUserData = function(){
$.getJSON("http://127.0.0.1:5000/data", function(data){
self.firstName(data.firstName);
self.lastName(data.lastName);
self.activities(data.activities);
self.favoriteHobby(data.favoriteHobby);
});
}
}
完整代码看起来像
Ajax的章节 - 7.html:
<html lang='en'>
<head>
<title>External data</title>
<meta charset='utf-8' />
<link rel='stylesheet' href='style.css' />
</head>
<body>
<h1>External data</h1>
<form action="#" method="post">
<p>
First name: <input data-bind='value: firstName' />
</p>
<p>
Last name: <input data-bind='value: lastName' />
</p>
<div>
Your favorite hobby:
<select data-bind='options: activities, value: favoriteHobby'></select>
</div>
<p>
<button data-bind='click: loadUserData'>Load Data</button>
</p>
</form>
<script type='text/javascript' src='knockout-3.4.0.js'></script>
<script type='text/javascript' src='jquery-3.1.1.min.js'></script>
<script type='text/javascript'>
function PersonViewModel(){
var self = this;
self.firstName = ko.observable("");
self.lastName = ko.observable("Johnson");
self.activities = ko.observableArray([]);
self.favoriteHobby = ko.observable("");
// http://stackoverflow.com/questions/25011952/can-you-add-headers-to-getjson-in-jquery
$.ajaxSetup({
headers: {
// 'Origin': 'http://example.com'
}
})
self.loadUserData = function(){
$.getJSON("http://127.0.0.1:5000/data", function(data){
Object.keys(data).forEach(function(k){
alert(k);
alert(data[k]);
alert(self[k]);
self[k] = data[k];
});
// self.firstName(data.firstName);
// self.lastName(data.lastName);
// self.activities(data.activities);
// self.favoriteHobby(data.favoriteHobby);
});
}
}
ko.applyBindings(new PersonViewModel());
</script>
</body>
</html>
server.py:
from flask import Flask, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello():
return 'Hello, world'
# http://stackoverflow.com/questions/13081532/how-to-return-json-using-flask-web-framework
@app.route('/data')
def data():
data = {
'firstName': 'Cody',
'lastName': 'Childers',
'activities': [
'Golf',
'Kayaking',
'Web development',
],
'favoriteHobby': 'Golf',
}
return jsonify(**data)
if __name__ == "__main__":
app.run()
书和代码都有效,但loadUserData
是可怕的和重复的。在python中我们可以这样做:
keys = ['firstName', 'lastName', 'activities', 'favoriteHobby']
for key in keys:
setattr(self, key, getattr(data, key))
热潮,完成了。
假设我知道我得到的JSON密钥与我想设置的属性名称相同,是否有一个Javascript等同于在字符串上设置self属性?
Knockout将要求我将属性作为一个函数调用,而不是将它们设置为普通属性(knockout将其称为'observables')。
谢谢
答案 0 :(得分:3)
您可以使用括号表示法和Object.keys()
$.getJSON("http://127.0.0.1:5000/data", function(data){
Object.keys(data).forEach(function(k) {
// you may check if the key is in the "to be transferred ones" here
self[k] = data[k];
});
});
如果您只想指定某些键,可以使用
var allowedKeys = ['firstName', 'lastName', 'activities', 'favoriteHobby']
$.getJSON("http://127.0.0.1:5000/data", function(data){
Object.keys(data).forEach(function(k) {
if (allowedKeys.indexOf(k) > -1) self[k] = data[k];
});
});
或者,您也可以使用Object.assign()
,但无法排除某些键:
$.getJSON("http://127.0.0.1:5000/data", function(data){
self = Object.assign(self, data);
});
对于你的评论,如果你需要调用一个函数(虽然你应该在执行之前添加一个检查函数是否存在):
$.getJSON("http://127.0.0.1:5000/data", function(data){
Object.keys(data).forEach(function(k) {
// you may check if the key is in the "to be transferred ones" here
self[k](data[k]);
});
});