【问题标题】:Execute a php page in background from ajax call从ajax调用在后台执行一个php页面
【发布时间】:2020-08-02 08:45:08
【问题描述】:

我有这个tab.php 页面,它基本上是网站的索引。它包含所有 JavaScript 和 HTML 代码。

我正在尝试从这个页面发送一些数组到 PHP 页面,而不是执行更新查询,将数组上传到我的 phpmyadmin。

我在tab.php 中使用了这段代码,但它不起作用。

 var send_array = {
"red": redtruppe,
"blue": bluetruppe,
"orange": orangetruppe,
"purple": purpletruppe,
"black": blacktruppe,
"green": greentruppe
};

$.ajax({ 
   type: "POST", 
   url: "send.php", 
   data: { TruppeJson : send_array }, 
   success: function() { 
          alert("Success"); 
    } 
}); 

send.php 页面现在是这样的:

<?php
$myTruppe = json_decode($_POST['TruppeJson']);
echo '<script>console.log('.$myTruppe.')</script>';
?>

成功警报似乎有效,但send.php 显然无效,有什么建议吗?

【问题讨论】:

  • send.php 以什么方式失败? &lt;script&gt;console.log.....etc 将是 POST 请求返回的数据...如果您有 success: function(result) { alert(result); },您会看到警告文本,即它会警告 &lt;script&gt;console.log('... the json will be here ...')&lt;/script&gt; - 可能不是您所期望的,但这就是您所写的跨度>
  • 首先感谢您的回答,我尝试使用 "success: function(result) { alert(result); }" 并更改 echo 但是,我的 json 文件似乎是空的
  • 没有json文件
  • 对不起,我的意思是数组

标签: javascript php arrays json ajax


【解决方案1】:

尝试将其用于数据:

 JSON.stringify(send_array)

并将您的数据类型定义为 JSON

dataType: "json"

看起来像这样:

$.ajax({ 
   type: "POST", 
   url: "send.php", 
   data: JSON.stringify(send_array),
   dataType: "json",
   success: function() { 
          alert("Success"); 
    } 
}); 

正如你所说,成功是被召唤的。所以你的数据不只是被发送到后端。

【讨论】:

  • 谢谢,我试过了,但现在没有成功
猜你喜欢
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 2019-11-06
相关资源
最近更新 更多