如何获取AJAX响应的值 [英] How to get values of the AJAX Response
问题描述
我不是要从AJAX调用的结果中获取值.我返回JSON,但不知道如何获取值.这是我的代码:
I am not to getting the values from the result of the AJAX call. I return JSON but I do not know how to get a value. This is my code:
$.ajax({
method: 'POST',
dataType: 'json',
url: 'queryProduct.php',
data: { codigo: cod }
}).done(function(response){
// How do it get values???
});
PHP文件结果:
$query = "SELECT * FROM produccion.ma_producto WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
if (!$result) {
echo "Error query: " . pg_last_error($conn);
} else {
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
}
从第一个使用ajax进行jquery调用的php文件中,在我想获取值并将其设置为其他元素之后....
From the first jquery call php file with ajax and after I would like to get the values and set to others elements....
推荐答案
$row = pg_fetch_row($result)
echo json_encode($row);
$row = pg_fetch_row($result)
echo json_encode($row);
在您的PHP文件中使用以上代码.
Use above code in your PHP file.
考虑AJAX调用会返回此JSON数组.
Consider AJAX call returns this JSON Array.
即
response = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
现在,在AJAX调用成功之后,您要遍历此数组的每个JSON对象,其中每个对象为{ color: 'someValue', value : 'someValue'}
.您可以使用item.color
和item.value
来访问它们.
Now, after success of AJAX call you want to iterate through each JSON Object of this array, Where each Object is { color: 'someValue', value : 'someValue'}
. You can use item.color
and item.value
to access them.
您可以执行以下操作:
$.ajax({
method: 'POST',
dataType: 'json',
url: 'queryProduct.php',
data: { codigo: cod },
success: function(response) {
console.log(response.pagino);
});
在这里,响应是您的JSON数组,而item表示JSON数组的对象.
Here, response is your JSON Array and item represents an Object of JSON Array.
您可以使用item.fieldName
从每个JSON对象访问每个字段.
You can use item.fieldName
to access each of your field from each JSON Object.
这篇关于如何获取AJAX响应的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!