简体   繁体   English

将JSON发送到PHP文件并在JS中接收响应

[英]Sending JSON to PHP file and Recieving Response in JS

I have looked at many other questions on here and I have tried many different methods but none seem to work. 我在这里查看了许多其他问题,并且尝试了许多不同的方法,但似乎没有一个起作用。

Heres my javascript file 这是我的JavaScript文件

function sendData() {
     var jsondata;
     var j = {"pub_id":"'+pid+'","a_type":"'+a_t'","p_domain":"'+domain+'"}
     var str_j = JSON.stringify(j);

     var xhr = new XMLHttpRequest();
     xhr.open("POST", "https://ads.schlarman.org/zz.php", !0);
     xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
     xhr.onreadystatechange = function() {
       if (xhr.readyState === 4 && xhr.status === 200) {
         jsondata = JSON.parse(xhr.responseText);
         console.log(jsondata);
       }
     }
}
sendData();

then zz.php 然后zz.php

<?php 
   header('Content-type: application/json');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true);
   $json_encode = json_encode($json_decode);
   echo $json_encode;
?>

If at all possible, build your json strings from actual javascript arrays/objects 如果有可能,请从实际的 javascript数组/对象构建json字符串

var j = {"pub_id":"'+pid+'","a_type":"'+a_t'","p_domain":"'+domain+'"};

could & probably should be 可能而且可能应该

var j = {"pub_id": pid, "a_type": a_t, "p_domain": domain};

Also, try adding the following header to your php 另外,尝试将以下标头添加到您的php中

Access-Control-Allow-Origin: *

More info here: https://enable-cors.org/server.html 此处提供更多信息: https : //enable-cors.org/server.html

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

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