Last active
August 29, 2015 14:19
-
-
Save Shinpeim/90ff614d71581b16f0b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Person(firstName, lastName){ | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
Person.prototype.greet = function(){ | |
alert("hello! I'm " + this.firstName + " " + this.lastName); | |
} | |
var p = new Person("shinpei", "maruyama"); | |
// できないやつ | |
$.ajax({ | |
type: "POST", | |
url: "./inc/test.php", | |
data: { | |
"person":p // これはできない!!!!! | |
}, | |
}); | |
// メソッドを持つようなやつが送れないなら、 | |
// オブジェクトを単純なデータに変換するメソッドを作ればよい | |
Person.prototype.asJson = function(){ | |
return {firstName: this.firstName, lastName: this.lastName}; | |
} | |
// できるやつ | |
$.ajax({ | |
type: "POST", | |
url: "./inc/test.php", | |
data: { | |
// p.asJson()は{firstName:"shinpei", lastName:"Maruyma"}という | |
// 単純なデータなのでAJAXで送れる | |
"person":p.asJson() | |
}, | |
}); | |
// 受け取るときも単純なデータをPHPから受け取って | |
// それをもとにオブジェクトを作れば良い | |
var json = {"firstName":"shinpei", "lastName":"Maruyma"}; // をPHP側から受け取り | |
var p2 = new Person(json.firstName, json.lastName); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment