在jQuery ajax调用之后将SQL数据返回到JavaScript中。

时间:2022-10-08 08:43:02

I'm pretty new to ajax (via jQuery) and JavaScript. What I would like is to execute a php script periodically (and asynchronously) that fetches some SQL data. However I will present this data in a JavaScript graph, so I need it to get back into my JavaScript.

我对ajax(通过jQuery)和JavaScript非常熟悉。我想要的是定期(并异步地)执行一个php脚本,获取一些SQL数据。但是我将在JavaScript图中显示这些数据,所以我需要它返回到我的JavaScript中。

I tried an embedded php script inside the JavaScript that pushes the SQL data into an array, and then simply fetches the page itself with .ajax call, but this did not work (even though I could see in the page source that the JavaScript was changed, the graph did not respond to the changes):

我试着嵌入式php脚本内部JavaScript将SQL数据到一个数组,然后简单地获取页面本身. ajax调用,但这并不工作(尽管我可以看到的页面源代码JavaScript被改变,图没有回应变化):

ajax.php (not working):

ajax。php(工作):

$(function () {        
   function fetchData() {            
   $.ajax('ajax.php');
   <?php        
   try
   {
      $now = time();
      $query = "select * from jet_pressure;"        
      $result = $db->query($query);
      foreach ($result as $row)
      {                                      
         print "d1.push([".$row['timestamp'].",".$row['unknown']."]);";            
      }                                
   }
   catch (Exception $e)
   {
      print 'Exception : '.$e->getMessage();
   }
   ?>           
   $.plot($("#placeholder"), [ d1]);
   setTimeout(fetchData, 5000);
   }    
    setTimeout(fetchData, 500);    
   });       

What is the recommended way to do this?

推荐的方法是什么?

2 个解决方案

#1


3  

I think you are mixing up your concepts. PHP only runs on the webserver. Javascript runs on the client (ie the web browser)

我认为你混淆了你的概念。PHP只在webserver上运行。Javascript在客户机上运行(即web浏览器)

If you create a page with the .php extension as in your ajax.php, it will be served from you web server once and everything it contains that's a in the <?php ?> block will be parsed by the server - it not dynamic.

如果您在ajax中创建一个带有.php扩展名的页面。php,它将从web服务器上服务一次它包含的所有内容都是 块将由服务器解析——它不是动态的。

The resultant page contains parsed values from your php script, but not the script itself.

生成的页面包含php脚本的解析值,但不包含脚本本身。

Javascript operates on the users computer, and therefore handles the user interaction and events on the web page. You can use Javascript to call a server script (in this case php) when you need to get data from the server. That is basically what AJAX is all about. But generally the javascript is contained in files ending .js which tend not to be parsed by your webserver, unless the javascript is actually included in your page, but that's not really how to do things these days.

Javascript在用户计算机上运行,因此处理web页面上的用户交互和事件。当需要从服务器获取数据时,可以使用Javascript调用服务器脚本(在本例中是php)。这就是AJAX的本质。但是javascript通常包含在以.js结尾的文件中,这些文件通常不会被web服务器解析,除非javascript实际上包含在页面中,但这并不是现在真正的方法。

I have no idea what you are tring to do by mixing javascript with php. This is not AJAX.

我不知道把javascript和php混在一起做什么。这不是AJAX。

I suggest you use something like JSON. This rough php script first to compile your results into JSON, then the javascript ajax call. You'll need to have included the JQUERY library and save the whole php script as a seperate file called getdata.php.

我建议您使用JSON之类的东西。这个简单的php脚本首先将结果编译成JSON,然后调用javascript ajax。您需要包含JQUERY库,并将整个php脚本保存为一个名为getdata.php的分离文件。

<?php
// You'll have to do all the database select stuff here


    while ($Row = mysql_fetch_array($params)) 
{      
    $jsondata[]= array('jsobjectfield1'=>$Row["dbtablefield1"],
        'jsobjectfield2'=>$Row["dbtablefield2"],                       'jsobjectfield3'=>$Row["dbtablefield3"],                      'jsobjectfield4'=>$Row["dbtablefield4"]); 
};  
echo("{\"TableData\": ".json_encode($jsondata)."};");

?>

Javascript:

Javascript:

$.ajax({
    url: 'getdata.php',
    type: "POST",
    data: entereddata,
    dataType: "json",
    timeout: (7000),
    //wait 7 seconds          
    error: function(data)          
    {                     

    }, //end of ERROR handling          
    success: function(data)          
    {  
        // you'll find the data returned here:
    data.jsobjectfield1   
    }; // end of SUCCESS handling 

}); // end AJAXcall 

#2


0  

HI I dont think you can do that directly.... If you want to pass data back and forth between PHP and JS u need to use xml http request .. you could find a very good tutorial that will help you a lot here ...... http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php hope that helps ... it sure helped me when I was starting .... I was trying to do the same thing that you are trying to do and then I knew that I was trying to mix up server and client side scripting

你好,我觉得你可以直接....如果您想在PHP和JS之间来回传递数据,需要使用xml http请求。你可以在这里找到一个很好的教程来帮助你http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php希望这能有所帮助……确实帮助我当我开始....我试着做你想做的事情,然后我知道我在尝试把服务器端脚本和客户端脚本混合在一起

what you do here is following ....

你做什么这是....后

1 pass a list of parameters to php

将参数列表传递给php

2 php does some processing (in your case query database) and echoes the desired output variables

php执行一些处理(在您的案例查询数据库中)并响应所需的输出变量

3 that are returned to JS

3返回给JS

If you are looking for direct code ... there you go .... the credit goes to the site I have mentioned above its not my code ... I really recommend you go to that site ... you will learn a lot in a short time .... hope that helps

如果您正在寻找直接代码……这是你们要的....我上面提到的网站不是我的代码……我真的建议你去那个网站……你会在短时间内学到很多....希望这有助于

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("GET", "serverTime.php", true);
    ajaxRequest.send(null); 
}

//-->
</script>



<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

serverTime.php

serverTime.php

<?php
echo date("H:i:s"); 
?>

#1


3  

I think you are mixing up your concepts. PHP only runs on the webserver. Javascript runs on the client (ie the web browser)

我认为你混淆了你的概念。PHP只在webserver上运行。Javascript在客户机上运行(即web浏览器)

If you create a page with the .php extension as in your ajax.php, it will be served from you web server once and everything it contains that's a in the <?php ?> block will be parsed by the server - it not dynamic.

如果您在ajax中创建一个带有.php扩展名的页面。php,它将从web服务器上服务一次它包含的所有内容都是 块将由服务器解析——它不是动态的。

The resultant page contains parsed values from your php script, but not the script itself.

生成的页面包含php脚本的解析值,但不包含脚本本身。

Javascript operates on the users computer, and therefore handles the user interaction and events on the web page. You can use Javascript to call a server script (in this case php) when you need to get data from the server. That is basically what AJAX is all about. But generally the javascript is contained in files ending .js which tend not to be parsed by your webserver, unless the javascript is actually included in your page, but that's not really how to do things these days.

Javascript在用户计算机上运行,因此处理web页面上的用户交互和事件。当需要从服务器获取数据时,可以使用Javascript调用服务器脚本(在本例中是php)。这就是AJAX的本质。但是javascript通常包含在以.js结尾的文件中,这些文件通常不会被web服务器解析,除非javascript实际上包含在页面中,但这并不是现在真正的方法。

I have no idea what you are tring to do by mixing javascript with php. This is not AJAX.

我不知道把javascript和php混在一起做什么。这不是AJAX。

I suggest you use something like JSON. This rough php script first to compile your results into JSON, then the javascript ajax call. You'll need to have included the JQUERY library and save the whole php script as a seperate file called getdata.php.

我建议您使用JSON之类的东西。这个简单的php脚本首先将结果编译成JSON,然后调用javascript ajax。您需要包含JQUERY库,并将整个php脚本保存为一个名为getdata.php的分离文件。

<?php
// You'll have to do all the database select stuff here


    while ($Row = mysql_fetch_array($params)) 
{      
    $jsondata[]= array('jsobjectfield1'=>$Row["dbtablefield1"],
        'jsobjectfield2'=>$Row["dbtablefield2"],                       'jsobjectfield3'=>$Row["dbtablefield3"],                      'jsobjectfield4'=>$Row["dbtablefield4"]); 
};  
echo("{\"TableData\": ".json_encode($jsondata)."};");

?>

Javascript:

Javascript:

$.ajax({
    url: 'getdata.php',
    type: "POST",
    data: entereddata,
    dataType: "json",
    timeout: (7000),
    //wait 7 seconds          
    error: function(data)          
    {                     

    }, //end of ERROR handling          
    success: function(data)          
    {  
        // you'll find the data returned here:
    data.jsobjectfield1   
    }; // end of SUCCESS handling 

}); // end AJAXcall 

#2


0  

HI I dont think you can do that directly.... If you want to pass data back and forth between PHP and JS u need to use xml http request .. you could find a very good tutorial that will help you a lot here ...... http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php hope that helps ... it sure helped me when I was starting .... I was trying to do the same thing that you are trying to do and then I knew that I was trying to mix up server and client side scripting

你好,我觉得你可以直接....如果您想在PHP和JS之间来回传递数据,需要使用xml http请求。你可以在这里找到一个很好的教程来帮助你http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php希望这能有所帮助……确实帮助我当我开始....我试着做你想做的事情,然后我知道我在尝试把服务器端脚本和客户端脚本混合在一起

what you do here is following ....

你做什么这是....后

1 pass a list of parameters to php

将参数列表传递给php

2 php does some processing (in your case query database) and echoes the desired output variables

php执行一些处理(在您的案例查询数据库中)并响应所需的输出变量

3 that are returned to JS

3返回给JS

If you are looking for direct code ... there you go .... the credit goes to the site I have mentioned above its not my code ... I really recommend you go to that site ... you will learn a lot in a short time .... hope that helps

如果您正在寻找直接代码……这是你们要的....我上面提到的网站不是我的代码……我真的建议你去那个网站……你会在短时间内学到很多....希望这有助于

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("GET", "serverTime.php", true);
    ajaxRequest.send(null); 
}

//-->
</script>



<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

serverTime.php

serverTime.php

<?php
echo date("H:i:s"); 
?>