AJAX自动填充Cakephp 3表单

时间:2017-11-18 00:46:34

标签: javascript php jquery ajax cakephp

我正在尝试使用下拉菜单中所选客户的客户数据自动填写发票表单上的默认值。在下面照片中的下拉列表中选择客户后,我希望它自动填写下表中下一张照片中客户表中的数据地址。 enter image description here enter image description here

到目前为止,这是我的发票add.ctp脚本,用于尝试获取数据。目前使用此脚本,我可以获取选择在sql查询中使用的客户ID,还可以在表单输入中设置数据

<script>

            document.getElementById('customers').addEventListener('change',function(){
               alert(this.value);
            $('#customers').click(function(){
                $.ajax({
                    type: "POST",
                    url: '<?php echo Router::url(array('controller' => 'Customers', 'action' => 'fill')); ?>',
                    success: function(data){
                        alert(data);
                    }
                });
            });

            document.getElementById('name').value = "test"
            document.getElementById('invoice_to_address').value = "test"

            });

        </script>

这是我在CustomersController中的填充功能。这是我出错的地方我认为我的查询可能是完全错误的,并且它没有搜索正确的东西并且错误地返回它,甚至可能甚至没有使用表单中的客户ID。目前它只返回没有数据但也没有错误,并且由于视图中的脚本而出现空警告框。

 public function fill()
{
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    $data = array();

    $id = $this->request->data();
    $query = $this->Customers->find()
    ->where([
    'id' => $id]);

$this->set(array(
    'id' => $query,
    '_serialize' => 'id'
    ));    


}

更新

我的完整发票add.ctp

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<?php echo $this->Html->script('jquery.chained'); ?>
<script type="text/javascript">
    $(document).ready(function () {
        $("#contacts").chained("#customers");
    });
</script>
<?php use Cake\Routing\Router; ?>
<?php
/**
  * @var \App\View\AppView $this
  */
?>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <ul class="side-nav">
        <li class="heading"><?= __('Actions') ?></li>
        <li><?= $this->Html->link(__('List Invoices'), ['action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('List Customers'), ['controller' => 'Customers', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer'), ['controller' => 'Customers', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Customer Contacts'), ['controller' => 'CustomerContacts', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer Contact'), ['controller' => 'CustomerContacts', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Aircraft Registrations'), ['controller' => 'AircraftRegistrations', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Aircraft Registration'), ['controller' => 'AircraftRegistrations', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Shipping Companies'), ['controller' => 'ShippingCompanies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Shipping Company'), ['controller' => 'ShippingCompanies', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Job Types'), ['controller' => 'JobTypes', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Job Type'), ['controller' => 'JobTypes', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Currencies'), ['controller' => 'Currencies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Currency'), ['controller' => 'Currencies', 'action' => 'add']) ?></li>
    </ul>
</nav>
<div class="invoices form large-9 medium-8 columns content">
    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php
            echo $this->Form->input('start_date', ['empty' => false]);
            echo $this->Form->input('close_date', ['empty' => true]);
            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
            echo $this->Form->input('name', ['type' => 'text', 'id'=>'name']);
            echo $this->Form->input('invoice_to_address', ['type' => 'text', 'id'=>'invoice_to_address']);
            echo $this->Form->input('ship_to_address');
            echo $this->Form->input('customer_contact_id', ['options' => $customerContacts, 'empty' => true,'id'=>'contacts']);
            echo $this->Form->input('currency_id', ['options' => $currencies, 'default'=> 1, 'id'=>'currencies']);
        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
    <?= $this->Form->create(Null, ['type' => 'POST']) ?>
    <?= $this->Form->end() ?>
</div>

<script>
        jQuery('#name').autocomplete({source:'<?php echo Router::url(array('controller' => 'Customers', 'action' => 'search')); ?>'
        });
</script>

<script>
    document.getElementById('customers').addEventListener('change',function(){
       var id = this.value;
       alert(id);
        var csrfToken = $('[name=_csrfToken]').val();
        $.ajax({
            type: "POST",
            url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
            data: {'id' : id},
            beforeSend: function(xhr){
               xhr.setRequestHeader('X-CSRF-Token', csrfToken);
            },
            success: function(data){
                alert(data);
                data = JSON.parse(data);
                alert("id: " + data.id);
            }
        });
    document.getElementById('name').value = "test"
    document.getElementById('invoice_to_address').value = "test"
    document.getElementById('currencies').value = 3;
    });

</script>

和控制器填充功能

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);  
    }  
}

当($ this-&gt; request-&gt;是('ajax'))存在时会发生什么。没有回应或预览。 enter image description here

当if($ this-&gt; request-&gt;是('ajax'))被删除时。 enter image description here

以下是完整的错误消息

{"id":0,"name":"Sky Works","country_id":1,"city_id":6,"address":"Sky works address in the customers table","postal_address":"Sky works shippng address in the customers table","phone":"","email":"","payment_terms_id":1,"stop_credit":false,"gst_percentage":null,"currency_id":"2","account_closed":false,"invoice_email":"","customer_notes":""}<pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-trace').style.display = (document.getElementById('cakeErr5a1140bb8332d-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (512)</a>: Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179 [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>48</b>]<div id="cakeErr5a1140bb8332d-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-code').style.display = (document.getElementById('cakeErr5a1140bb8332d-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-context').style.display = (document.getElementById('cakeErr5a1140bb8332d-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb8332d-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$message&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #DD0000">"Unable&nbsp;to&nbsp;emit&nbsp;headers.&nbsp;Headers&nbsp;sent&nbsp;in&nbsp;file=</span><span style="color: #0000BB">$file</span><span style="color: #DD0000">&nbsp;line=</span><span style="color: #0000BB">$line</span><span style="color: #DD0000">"</span><span style="color: #007700">;</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">if&nbsp;(</span><span style="color: #0000BB">Configure</span><span style="color: #007700">::</span><span style="color: #0000BB">read</span><span style="color: #007700">(</span><span style="color: #DD0000">'debug'</span><span style="color: #007700">))&nbsp;{</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;trigger_error</span><span style="color: #007700">(</span><span style="color: #0000BB">$message</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">E_USER_WARNING</span><span style="color: #007700">);</span></span></code></pre><pre id="cakeErr5a1140bb8332d-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$maxBufferLength = (int) 8192
$file = &#039;/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php&#039;
$line = (int) 179
$message = &#039;Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179&#039;</pre><pre class="stack-trace">Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 48
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre><pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-trace').style.display = (document.getElementById('cakeErr5a1140bb8392c-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (2)</a>: Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>146</b>]<div id="cakeErr5a1140bb8392c-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-code').style.display = (document.getElementById('cakeErr5a1140bb8392c-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-context').style.display = (document.getElementById('cakeErr5a1140bb8392c-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb8392c-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$response</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getStatusCode</span><span style="color: #007700">(),</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">(</span><span style="color: #0000BB">$reasonPhrase&nbsp;</span><span style="color: #007700">?&nbsp;</span><span style="color: #DD0000">'&nbsp;'&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #0000BB">$reasonPhrase&nbsp;</span><span style="color: #007700">:&nbsp;</span><span style="color: #DD0000">''</span><span style="color: #007700">)</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">));</span></span></code></pre><pre id="cakeErr5a1140bb8392c-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;OK&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$reasonPhrase = &#039;OK&#039;</pre><pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitStatusLine() - CORE/src/Http/ResponseEmitter.php, line 146
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 54
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre><pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-trace').style.display = (document.getElementById('cakeErr5a1140bb83ee9-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (2)</a>: Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>173</b>]<div id="cakeErr5a1140bb83ee9-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-code').style.display = (document.getElementById('cakeErr5a1140bb83ee9-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-context').style.display = (document.getElementById('cakeErr5a1140bb83ee9-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb83ee9-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$name</span><span style="color: #007700">,</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$value</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">),&nbsp;</span><span style="color: #0000BB">$first</span><span style="color: #007700">);</span></span></code></pre><pre id="cakeErr5a1140bb83ee9-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;OK&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$name = &#039;Content-Type&#039;
$values = [
    (int) 0 =&gt; &#039;text/html; charset=UTF-8&#039;
]
$first = true
$value = &#039;text/html; charset=UTF-8&#039;</pre><pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitHeaders() - CORE/src/Http/ResponseEmitter.php, line 173
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 55
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre>

2 个答案:

答案 0 :(得分:0)

更改:

$query = $this->Customers->find()->where(['id' => $id]); 

致:

$query = $this->Customers->find()->where(['id' => $id])->first();

也使用&#34; echo&#34;在控制器中将数据返回给ajax。

echo json_encode($query);

然后应该返回json编码的数据。

修改
确保在ctp文件中创建了一个表单(获取csrf标记):

<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?= $this->Form->end() ?>

并将这些行添加到javascript代码中:

beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},

并添加&#34;数据&#34;到javascript,如:

var id = 1; //Your ID. I don't know what ID it is, so I just use 1. 
var csrfToken = $('[name=_csrfToken]').val(); //Sorry, I forgot this.
$.ajax({
    type: "POST",
    url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    beforeSend: function(xhr){
       xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});

更改控制器:

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);  
    }  
}

修改
也许你没有使用CsrfToken。在这种情况下,您不需要加载CsrfToken。 像这样更改javascript代码:

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  //jQuery CDN. If you have loaded jQuery somewhere else, you don't need this.  
</script> 
<script>
var id = 1; //Your ID. I don't know what ID it is, so I just use 1. 
$.ajax({
    type: "POST",
    url: '<?= $this->Url->build(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});
</script>

使用此javascript,我认为您不必更改控制器(您不需要删除(&#39; ajax&#39;)。)

修改
也许如你所说,从控制器返回null。但我想检查错误消息是什么。请通过以下方式检查。

如果成功,则获得json字符串。您可以在收到后将其更改为javascript的对象。 enter image description here

如果失败,您可以从Google Chrome浏览器进行检查。它应该显示你得到的错误: enter image description here

或者,也许cakephp可能会在html中返回错误消息。在这种情况下,你会收到这个: enter image description here

这是原始的html代码,因此可能很难阅读。

请告诉我您收到的错误消息..

答案 1 :(得分:0)

这是Lechien。

似乎错误消息是:无法发出标头。在文件= / home / southpac / southpacificavionics.com / team / src / Controller / CustomersController.php第179行发送的标题。

从错误消息中,我怀疑BOM是否已添加到任何PHP文件中。请在此处查看问题:How to fix "Headers already sent" error in PHP
有时,Windows默认文本编辑器会自动将BOM添加到文件中。

您可以检查客户的控制器文件和模板(ctp文件)中是否有BOM?如果发现添加了BOM,请删除BOM。然后我提供的代码应该可以工作。