简体   繁体   English

将数据集从PHP传递到javascript验证

[英]Pass dataset to a javascript validation from PHP

I am trying to minimise postback in my web app. 我正在尝试最小化Web应用程序中的回发。 I have a number of inter-dependent dropdowns, an onselectedindexchange event fires for each one which obviously causes a postback. 我有很多相互依赖的下拉菜单,每个触发器都会触发一个onselectedindexchange事件,这显然会导致回发。 Is there a way I can get all my data from a dataset\\datareader into some javascript arrays and then use client side events to handle the inter-dependent dropdowns? 有没有一种方法可以将我的所有数据从数据集\\数据读取器获取到一些javascript数组中,然后使用客户端事件来处理相互依赖的下拉列表? Any code examples? 任何代码示例?

Sure, just echo the JSON encoded data inside a script tag: 当然,只需在script标记内回显JSON编码的数据即可:

<head>
<script type="text/javascript">
var dataset = <?php echo json_encode($dataSetAsPhpArray); ?>
</script>
</head>

dataset will be a JS array or object depending on what kind of PHP array $dataSetAsPhpArray was. dataset将是一个JS数组或对象,具体取决于$dataSetAsPhpArray是哪种PHP数组。 Numerically indexed array results in JS array, while assoc array results in JS object. 数值索引数组产生JS数组,而assoc数组产生JS对象。

Use Javascript Object Notation. 使用Javascript对象表示法。 JSON is a method for other languages to pass information to javascript. JSON是其他语言将信息传递给javascript的一种方法。 PHP has a function encode_json( $array_of_data ); PHP有一个函数encode_json($ array_of_data); You should be able to do something like: 您应该能够执行以下操作:

 Header( 'Content-type:json' );
 //gather data
 echo json_encode( $your_data );

If you are using jQuery the Javascript code would look like 如果您使用的是jQuery,则Javascript代码看起来像

 $.ajax({
   url: your_url,
   type: GET or POST,
   dateType: json,
   success: function(){
     //manipulate dom here
   }
 });

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

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