简体   繁体   English

如何使用ajax在函数内放置元素数组?

[英]How to place an array of elements inside a function with ajax?

 var answered = ["john","jay","mark"];

 function tick(){

   $("#btn_wys").on('click', function(){

     var name = $('input#name').val();
     var num = $('input#num').val();

     if ($.trim(name)!= ''){
       $.post('wys.php', {name: name, num: num},function(data){
          $('div#name-data').text(data);
     });
    }
 }

How will I pass the array "answered" such that variables name, num, and answered will be read on the wys.php using ajax. 我将如何传递数组“已回答”,以便使用ajax在wys.php上读取变量名称,数字和已回答。

inside wys.php is a query that will echo 1 or 0. 在wys.php内部的查询将回显1或0。

additional question: will I be able to add new element inside the array 'answered' if wys.php echoes 1 ? 附加问题:如果wys.php回显1,是否可以在“已回答”数组中添加新元素? If yes, how? 如果是,怎么办?

I think this is all you need 我想这就是你所需要的

var answered = ["john","jay","mark"];

//run function 
tick(answered);

function tick(answered){ // pass in function
  answered.push('Smith'); //insert new
  alert(answered[0]); // get the value number 1 in array
  alert(answered[1]); // get the value number 2 in array
  alert(answered[2]); // get the value number 3 in array
  alert(answered[3]); // get the value number 4 in array
  alert(answered.length); // how many values in array
}

Working Demo 工作演示

to pass it in php 通过PHP

{name: name, num: num , answered : answered}

and in php read it as array 并在PHP中将其读取为数组

<?php
 print_r($_POST['answered']);
?>

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

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