javascript - 如何使用数组变量将值从一个函数传递到另一个函数
问题描述
您好,我有一个函数可以使用 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() 的数组键值,而不是存储在数组中的内容值。但是这些值是在
解决方案
尝试json_encode($form_array)
使用 php 脚本并添加"JSON" as 4th param
jquery ajax。这样您就可以在回调中访问从 php 脚本发送的数据,例如response.email
推荐阅读
- python - 算法:IndexError:列表索引超出范围(Python)
- c++ - 为什么需要在索引中添加“0”才能访问数组值?
- swift - 是否只能使用 UITableViewController 使用两指平移手势选择多个项目?
- flutter - Flutter for Firestore 中的 Streambuilder
- python - 向可以从自定义基类访问的 celery 函数添加额外的属性
- ios - 将导航控制器推入导航控制器
- react-hooks - 将回调传递给自定义反应钩子
- python-3.x - 是否可以使用 Python tarfile 读取并附加到 tar
- anaconda - Anaconda 安装卡在 - '设置包缓存'
- flutter - 无法使用 Quckblox 和 Flutter 接收消息和传入事件