weixin_33724570 2017-11-18 00:46 采纳率: 0%
浏览 38

AJAX自动填充Cakephp 3表单

I am trying to auto fill defaults on my invoices form with customer data based off the customer selected in the drop down. Once the customer is selected in this drop down in the photo below I want it to auto fill the addresses from the data found in the customer table in the next photo below also. enter image description here enter image description here

So far this is my invoices add.ctp script to try fetch the data. Currently with this script I can fetch the customer id that was selected to use in a sql query and also set data in the forms inputs

<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>

This is my fill function in my CustomersController. This is where I am going wrong I think my query is probably completely wrong and it's not searching for the right thing and returning it incorrectly and probably not even using the customer ID from the form. Currently it just returns no data but also has no errors and an empty alert box comes up due to the script in the view.

 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'
    ));    


}

UPDATE

My full Invoices 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>

and the controller fill function

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);  
    }  
}

What happens when ($this->request->is('ajax')) is there. There's no response or preview. enter image description here

When if ($this->request->is('ajax')) is removed. enter image description here

Here is the full error message

{"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条回答 默认 最新

  • hurriedly% 2017-11-18 05:02
    关注

    Change:

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

    To:

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

    Also use "echo" in the controller to return the data to ajax.

    echo json_encode($query);
    

    Then json encoded data should be returned.

    Edit:
    Make sure you have created a form (to get csrf token) like this in the ctp file:

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

    And add these lines to the javascript code:

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

    And add "data" to javascript, like:

    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);
        }
    });
    

    And change the controller:

    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);  
        }  
    }
    

    Edit:
    Maybe you are not using CsrfToken. In that case, you don't need to load CsrfToken. Change the javascript code like this:

    <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>
    

    With this javascript, I think you don't have to change the controller (you don't need to remove is('ajax').)

    Edit
    Maybe as you say, null is returned from the controller. But I want to check what the error message is. Please check it by the following way.

    If succeeded, you get json string. You can change it to javascript's object after receiving it. enter image description here

    If failed, you can check it from the google chrome browser. It should show what error you get: enter image description here

    Or, maybe cakephp might return error message in html. In that case, you would receive this: enter image description here

    This is raw html code, so it might be hard to read.

    Please let me know what error message you get..

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置