使用AJAX再次传递变量到PHP和检索那些使用AJAX变量、AJAX、PHP

2023-09-10 13:18:39 作者:你在搞笑!

我想,所以我使用AJAX来传递的,而在同样的功能,我用另一种AJAX来检索这些值将值传递给PHP脚本。的问题是,在第二AJAX未检索从PHP文件中的任何值。为什么是这样?我怎么可以存储传递到PHP脚本,使得第二AJAX可以检索它的变量?我的code是如下:

AJAX code:

  $(文件)。就绪(函数(){
    $(#raaagh)。点击(函数(){
        $阿贾克斯({
            网址:'ajax.php',//这是当前文档
            键入:POST,
            数据:({名:145}),
            成功:功能(数据){
                的console.log(数据);
                           }
        });
        $阿贾克斯({
    网址:'ajax.php,
    数据:,
    数据类型:JSON,
    成功:函数(数据1){
            VAR Y1 = DATA1;
            执行console.log(DATA1);
            }
        });

    });
});
 

PHP code:

 < PHP

$ userAnswer = $ _ POST ['名称'];

回声json_en code($ userAnswer);
?>
 

解决方案 怎么得到这个ajax得到的值 我在外面定义了一个变量,可是值没传进去,获取的都是空值

使用数据类型:JSON JSON 数据

  $。阿贾克斯({
     网址:'ajax.php',//这是当前文档
     键入:POST,
     数据类型:'json的',//添加JSON数据类型来获得JSON
     数据:({名:145}),
     成功:功能(数据){
         的console.log(数据);
     }
});
 

阅读文档 http://api.jquery.com/jQuery.ajax/

此外,在 PHP

 < PHP
  $ userAnswer = $ _ POST ['名称'];
  $ SQL =SELECT * FROM< tablname化合物其中颜色='。$ userAnswer';
  $结果= mysql_query($ SQL);
  $行= mysql_fetch_array($结果);
  //为第一行只具有数据假设表
  回声json_en code($行);在json_en code //传递数组
?>
 

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values. The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it? My code is as follows:

AJAX CODE:

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

PHP CODE:

<?php

$userAnswer = $_POST['name'];    

echo json_encode($userAnswer);    
?>

解决方案

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

Read Docs http://api.jquery.com/jQuery.ajax/

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>