简体   繁体   English

如果可能将AJAX请求传递给Javascript函数的PHP变量?

[英]Pass PHP variable to Javascript function whitin an AJAX request possible?

I try to pass a variable from Javascript (when choosing some option in a form) to a PHP file which calls a SQL query. 我尝试将变量从Javascript(当在表单中选择某些选项时)传递给调用SQL查询的PHP文件。

The SQL query (a string) should be handed over to a Javascript function and the function should be executed. 应将SQL查询(字符串)移交给Javascript函数并执行该函数。 Everything in one click. 一键式完成所有操作。 Is that somehow possible? 有可能吗?

I tried that with a AJAX request but when I use this for my last step: 我尝试了AJAX请求,但是当我将其用于最后一步时:

var javascriptstring;
      $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });

I get the exception: Uncaught TypeError: Cannot set property 'innerHTML' of null 我收到异常:未捕获的TypeError:无法将属性'innerHTML'设置为null

And it prints out "undefined" 并打印出“未定义”

.HTML .HTML

  <!DOCTYPE html>
<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
     function showString(time) {
  if (time=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","getstring.php?q="+time,true);
  xmlhttp.send();

      var javascriptstring;
      $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });
        document.write(javascriptstring);
}
</script>
</head>
<body>

    <form>
    <select name="somestring" onchange="showString(this.value)">
    <option value="">No string selected</option>
    <option value="1">String 1</option>
    </select>
    </form>
    <br>
    <div id="txtHint"><b>String will be listed here...</b></div>

</body>
</html>

PHP PHP

<?php
$q = intval($_GET['q']);

$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
    die('Could not connect: ' . pg_errormessage($con));
}

$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);

    $string = "";
while($row = pg_fetch_assoc($result)){
    $lat = $row['latitude'];
    $lon = $row['longitude'];
    $string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo '{"value": "'.$string.'"}';
pg_close($con);
?>

You forget to close script tag 您忘记关闭脚本标签

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>// close include external javascript tag

Then you call your function inside script tag 然后在脚本标签内调用函数

<script>
function showString(time) {

-----Your code----

</script>

I guess this much amount of AJAX should suffice. 我想这么多的AJAX就足够了。 Actually document.write replaces the whole DOM with the current. 实际上document.write用当前替换了整个DOM。 I have removed that and modified your function. 我已删除它并修改了您的功能。 Also I have removed the native Ajax code since you already have jQuery so no point in adding that big code. 另外,由于您已经拥有jQuery,因此我已经删除了本地Ajax代码,因此添加大代码毫无意义。 This small function will get the JSON data and print the value that the server is sending 这个小函数将获取JSON数据并打印服务器发送的值

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
    if (time=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    } 
    $.getJSON('getstring.php?q='+time, function(data) {
      document.getElementById("txtHint").innerHTML = data.value;
    });
}
</script>

Edit: Please close the external script tags 编辑:请关闭外部脚本标签

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
  //your script
</script>

Keep the Javascript function definition in head or before the select tag. 将Javascript函数定义放在headselect标签之前。 like below - 像下面-

<!DOCTYPE html>
 <html>
   <head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
     <script type='text/javascript'>
       function showString(time) {
         if (time=="") {
         document.getElementById("txtHint").innerHTML="";
         return;
       } 
       if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState==4 && xmlhttp.status==200) {
          document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
         }
       }
       xmlhttp.open("GET","getstring.php?q="+time,true);
       xmlhttp.send();

       var javascriptstring;
       $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });
       document.write(javascriptstring);

     }

     </script>

   </head>
   <body>
     <form>
       <select name="somestring" onchange="showString(this.value)">
         <option value="">No string selected</option>
         <option value="1">String 1</option>
       </select>
     </form>
   </body>
 </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM