I am new to javascript so please be patient with me. I have a function in php which goes like this:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return $stmt->fetchall();
}
Then I have a variable subs in javascript which is hardocded like this:
var subs = {"Maths":1,"Geography":2,"Chmesitry":3,"Literature":4};
How do I populate the subs variable with the format above from the getSubjects method?
I like to use json_encode
to convert the array to json so it can be used as an array of objects in JS.
PHP:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return json_encode($stmt->fetchall());
}
In javascript:
var subs = <?php echo getSubjects(); ?>;
console.log(subs);
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.