向php请求信息

时间:2018-05-29 13:13:45

标签: javascript php html

我试图在php文件上请求信息并在<div id="1"...上插入html代码,但它没有显示错误,也没有向div插入任何内容。它在AJAX代码中出错了,或者问题在于html?

PD:php正确提取了json文件中的信息。

PHP

<?php
$jsonContents = file_get_contents('../data/data.json');
$data         = json_decode($jsonContents, true);

foreach ($data as $key => $value) {
    echo($value['url']);
};

HTML

<!Doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>SSL Checker</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
    <h5 class="my-0 mr-md-auto font-weight-normal">SSL Checker</h5>
</div>

<div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
    <h1 class="display-4">SSL Checker</h1>
    <p class="lead">SSL Checker</p>
</div>

<div class="container">
    <div class="row">
</div>
    <footer class="pt-4 my-md-5 pt-md-5 border-top">
        <div class="row">
            <div id="1" class="col-12 col-md">
                <form method="GET" onsubmit="start()">
                    <button type="submit" class="btn btn-lg btn-block btn-primary">Contact us</button>
                </form>
            </div>
        </div>
    </footer>
</body>
</html>

JS

function start() {
    $.ajax({
        type: 'GET',
        url: '/api/domain/showall.php',
        success: function (response) {
            document.getElementById("1").innerHTML = '<input type="text" value="<?php  foreach ($data as $key => $value) {echo($value['url']);?>'
        }
    });
}

2 个答案:

答案 0 :(得分:2)

你有两个基本问题。

  1. submit事件会在form而非button上触发,因此您永远不会调用start函数
  2. 如果您正在调用start函数,那么您无法停止表单提交...因此,当浏览器加载新页面时,Ajax请求将被取消。
  3. 使用JavaScript绑定事件处理程序,将其绑定到正确的元素,并阻止默认操作。

    $("form").on("submit", start);
    
    function start(event) {
        event.preventDefault();
        $.ajax(etc etc etc);
    }
    

    可能(有些不清楚)尝试将PHP源代码嵌入到您分配给innerHTML的字符串中时会遇到其他问题。请记住:

    • 默认情况下,PHP不会在.js个文件中运行
    • 如果您在<script>元素中有它,那么它将在页面发送到浏览器之前运行
    • 您可能通过在PHP中连接字符串来生成无效的JS

    发出Ajax请求然后完全忽略response中的数据也很奇怪。

答案 1 :(得分:1)

您应该考虑@Quentin向您解释的内容。现在,如果您想在ajax成功函数上访问您的php数据,您可以执行以下操作:

首先在你的php上你必须通过js返回你想要访问的数据。这样:

<?php
    $jsonContents = file_get_contents('../data/data.json');
    $data         = json_decode($jsonContents, true);

    return $data;

现在由于数据是JSON,你需要指定你的ajax响应是JSON格式,将'dataType:'json'添加到你的ajax:

$.ajax({
    type: 'GET',
    url: '/api/domain/showall.php',
    dataType: 'json',
    success: function (data) {
        // data contains all the info you need from PHP
        // Now you will need to loop through data and append it to your html
    }
});

您可以使用jquery

检查此question如何循环json数据