将json数组中的值写入javascript变量

时间:2022-04-19 14:00:15

How can i make make a variable in a javascript and give it a value from an json array?

我怎样才能在javascript中创建一个变量并从json数组中赋值?

The array is sent from a php script and looks like this:

该数组是从php脚本发送的,如下所示:

php

$stat = array("v1" => "$v1", "v2" => "$v2", "v3" => "$v3",
"v4" => "$v4", "v5" => "$v5", "pump" => "$pump", "flow" => "$flow");
echo json_encode(($stat));

html/javascript

$.ajaxSetup({ cache: false });
setInterval(function(){
$.getJSON('statusdata.php',function(data) {
$.each(data, function(key, val) {

// I try to do something like this..
var v1 = key[1];
var v2 = key[2];
and so on..

Then i want to use a variable to alert a popup-window with some kind of warning.

然后我想使用一个变量来警告弹出窗口带有某种警告。

Someting like:

if (v1 == 1){
run the popup function!
}

Can anyone help me?

谁能帮我?

1 个解决方案

#1


0  

You're using $.each wrong. If you're going to be assigning from data to a set up regular variables you need to do them all individually, not inside a loop.

你使用$ .each错了。如果您要将数据分配给设置常规变量,则需要单独执行所有操作,而不是在循环内。

$.getJSON('statusdata.php',function(data) {
  v1 = data["v1"];
  v2 = data["v2"];
}

#1


0  

You're using $.each wrong. If you're going to be assigning from data to a set up regular variables you need to do them all individually, not inside a loop.

你使用$ .each错了。如果您要将数据分配给设置常规变量,则需要单独执行所有操作,而不是在循环内。

$.getJSON('statusdata.php',function(data) {
  v1 = data["v1"];
  v2 = data["v2"];
}