简体   繁体   中英

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.

inside wys.php is a query that will echo 1 or 0.

additional question: will I be able to add new element inside the array 'answered' if wys.php echoes 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

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

and in php read it as array

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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