开发者

accessing database values in javascript

Well

The situation is we are using mysql.We have written the queries and extracted the result from the assoc array.Now how do we access the result from javascript.

  $query = "SELECT firstname FROM employees;
  $result = mysql_query( $query , $resou开发者_StackOverflow社区rce );
  $value= mysql_fetch_assoc( $result);
  extract( $value );

Now does the javascript code be like

 <script type="text/javascript">
 function somefunction(){
 var databasefield = document.getElementsByName("firstname").value;
  }
 </script>


You need to add the firstname value into your PHP-generated HTML somehow. You could output it as a Javascript variable, or you could output it as a hidden INPUT field.


You can write your PHP page to deliver a JSON string like:

callBack({employee:{firstName:'Jim', lastName:'Black'}});

Where callBack is a function that exist in your page before the script tag pointing to your PHP.

<script>
  function callBack(json){
    ...
  }
</script>
<script src="/request.php?some_param=234"></script>

This technique is called JSONP.


It depends on what you want to do with the data from the query. If you want programmatic access to lots of data from Javascript then one good way is to use JSON notation. Basically, your PHP script will generate a snippet of javascript source code that represents a collection of values or basic javascript objects. You could do this with typical PHP templating style, or you can use a JSON library for PHP that is used to respond to a request coming from javascript running in the browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜