简体   繁体   English

将javascript变量发送到php并打印出“Array”

[英]sent javascript variable to php and it prints out “Array”

I sent a JavaScript variable containing the innerHTML "Basic" to PHP with Ajax and sent an email with the variable and it returned "Array" as opposed to "Basic". 我使用Ajax向PHP发送了包含innerHTML“Basic”的JavaScript变量,并发送了一个包含变量的电子邮件,它返回“Array”而不是“Basic”。 I am confused. 我很困惑。

HTML: HTML:

<label class="plan-name">Plan name: <b id="somii-plan">Basic</b></label>

JavaScript/AJAX: 的JavaScript / AJAX:

var somiiPlan = document.getElementById('somii-plan').innerHTML;
var request = $.ajax({
     type: "POST",
     url: "somii-pay.php",
     dataType: "json",
     data: {
        "somiiPlan" : somiiPlan,
        "email" : email,
     }
  });

PHP: PHP:

$somiiPlan = ['somiiPlan'];
$email = $_POST['email'];

$email_to = "******";
$email_subject = "Somii Test Charge";
$email_message = "Your plan is: " . $somiiPlan;
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

Your JS looks fine as dataType is used to set what type of response will be ,not request. 你的JS看起来很好,因为dataType用于设置响应的类型,而不是请求。

Your PHP has problem 你的PHP有问题

$somiiPlan = ['somiiPlan'];

will be 将会

$somiiPlan = $_POST['somiiPlan'];

Here you were creating an array on $somiiPlan , not getting the post param so why its returning array. 在这里你在$ somiiPlan上创建了一个数组,没有得到post param,所以为什么它返回数组。

Also note as you are not sending any response back and you are not handling the response in JS,so it is not required to set any dataType. 另请注意,由于您没有发回任何响应,并且您没有在JS中处理响应,因此不需要设置任何dataType。 And if you are sending any response make sure you send it on JSON encoded form. 如果您要发送任何回复,请确保以JSON编码的形式发送。

Remove this: 删除这个:

dataType: "json",

that's what giving you the array. 这就是给你阵列的原因。

JSON encodes things into an array JSON将事物编码为数组

So remove the dataType line 因此删除dataType行

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

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