首页 > 解决方案 > 如何使用数组变量将值从一个函数传递到另一个函数

问题描述

您好,我有一个函数可以使用 javascript 将值传递给其他函数,而无需重新加载页面。

下面 javascript 的第一个操作从表单中获取值并通过回调函数 formbuilder_ajax_call 发送到 php。在我的 php 脚本中,我将这些表单值作为数组返回,以便我可以在其他函数中调用它。下面是我的代码:

Javascript

   jQuery("#button_to_load_data").click(function() {
   var email = $("#email").val();
   var other_email = $("#other_email").val();
   var subject = $("#subject").val();
   var sender = $("#sender").val();
   var message = $("#message").val();
   var form_name = $("#form_name").val();
   var content = getPlainHtml();
  //    alert(content);
 var data = {
    'action'   : 'formbuilder_ajax_call', // the name of your PHP function!
    'form_content' : content,           // another random value we'd like to pass
    'email' : email,
    'other_email' : other_email,
    'subject' : subject,
    'sender' : sender,
    'message' : message,
    'form_name' : form_name,
    
    };
    
    
   var data1 = {
    'action'   : 'make_short_code'
    }; 

 jQuery.post(ajaxurl, data, function(response) {
    jQuery("#receiving_div_id").html(response);
 });


 jQuery.post(ajaxurl, data1, function(response) {
    jQuery("#receiving_div_id").html(response);
 });

 });

PHP

 function formbuilder_ajax_call(){

 $form_content = trim($_POST['form_content']); // these values are from a form
 $email = trim($_POST['email']);
 $other_email = trim($_POST['other_email']);
 $subject = trim($_POST['subject']);
 $sender = trim($_POST['sender']);
 $message = trim($_POST['message']);
 $form_name = trim($_POST['form_name']);

 $form_array = array(); 

 $form_array = array(

 "form_content" => $form_content,
 "email" => $email,
 "other_email" => $other_email,
 "subject" => $subject,
 "sender" => $sender,
 "message" => $message,
 "form_name" => $form_name,

  );  


  return  $form_array;
  }


  function make_short_code() { 

  $get_mailinfo = formbuilder_ajax_call();


  var_dump($get_mailinfo);

  }

我正在使用 var_dump 查看在 make_short_code 中传递的内容,但它只是传递的来自 formbuilder_ajax_call() 的数组键值,而不是存储在数组中的内容值。但是这些值是在

标签: javascriptphpwordpresswordpress-shortcode

解决方案


尝试json_encode($form_array)使用 php 脚本并添加"JSON" as 4th paramjquery ajax。这样您就可以在回调中访问从 php 脚本发送的数据,例如response.email


推荐阅读